c++面向对象: public 继承, 虚方法, 动态绑定

た 入场券 2022-04-22 11:06 222阅读 0赞

title: ‘c++面向对象: public 继承, 虚方法, 动态绑定’
date: 2018-11-04 13:00:34
tags:

  • oop
  • public inheritance
  • virtual methods
  • dynamic binding
    categories: cpp
    blog: https://withas.me

学了java中的面向对象后再来学习c++的面向对象, 对两者设计理念上的差异有不少的体会: c++更多地考虑了程序的运行效率(默认静态绑定, 没有垃圾回收等), 把很多繁琐的操作留给了使用者; 而java是贯彻了面向对象的思维, 有一种彻头彻尾的面向对象的感觉, 而把一些背后的机制向使用者隐藏了. 这篇blog主要记录c++中public继承相关的内容.

Public Inheritance

c++中有public, protected, private三种继承方式, 其中public是最常用的.

public继承描述的是一种is-a的关系, derived-class是base-class的一个子集且一般是真子集. 比如从Student类可以派生出Cadre类, Cadre一定是Student, 而Student不一定是Cadre. 这种关系是单向的, 不具有对称性.

  1. class Student {
  2. private:
  3. int id;
  4. string name;
  5. public:
  6. int getId() const { return id; }
  7. void setId(int id) { Student::id = id; }
  8. const string &getName() const { return name; }
  9. void setName(const string &name) { Student::name = name; }
  10. };
  11. class Cadre : public Student {
  12. private:
  13. string duty;
  14. public:
  15. const string &getDuty() const { return duty; }
  16. void setDuty(const string &duty) { Cadre::duty = duty; }
  17. };

Cadre由Student派生, 则Cadre直接继承了Student的所有public成员. Private成员也成为了derived-class的一部分, 但是只能通过base-class的public和protected方法访问. 例如Cadre从Student那里继承了name, 但是不能直接访问, 只能通过Student::getName访问.

  1. class Cadre : public Student {
  2. ...
  3. public:
  4. ...
  5. void showInfo() const {
  6. cout << Student::getName() << endl;
  7. cout << Student::getId() << endl;
  8. cout << duty << endl;
  9. }
  10. };

Constructos and Destructos

  1. class Student {
  2. private:
  3. int id;
  4. string name;
  5. public:
  6. Student(int id, const string &name) : id(id), name(name) { }
  7. ...
  8. };
  9. class Cadre : public Student {
  10. private:
  11. string duty;
  12. public:
  13. Cadre(int id, const string &name, const string &duty) : Student(id, name), duty(duty) { }
  14. ...
  15. };

Derived-class不能直接直接访问继承自base-class的private成员, 所以不能在constructors里直接对它们初始化, 必须借助base-class的constructors. 并且base-class必须先于derived-class被构造. 如果要使用base-class的constructor有参数则必须在derived-class的constructor中以初始化参数列表的方式调用, 如上例. 如果不在derived-class的constructor中显式地调用base-class的constructor, 则默认使用base-class的不带参数的constructor(不存在则编译会产生错误).

Base-class会先于derived-class被构造. 析构的方向恰与之相反, derived-class的destructor先于base-class被执行.

Is-a

前面提到过public继承是一种is-a的关系, 所以base-class的指针可以指向derived-class的对象, base-class的引用可以引用derived-class的对象.

  1. Student *pc = new Cadre(1, "J", "monitor");
  2. Student &rc = *pc;

但是通过base-class的指针和引用只能使用base-class存在的属性, 如:

  1. rc.getId();//ok
  2. rc.getDuty();//error

Virtual Methods

Redefine

有时候为了让derived-class有不同的功能我们可能需要重写base-class的方法.

  1. class Student {
  2. private:
  3. int id;
  4. string name;
  5. public:
  6. void showInfo() const {
  7. cout << name << endl;
  8. cout << id << endl;
  9. }
  10. };
  11. class Cadre : public Student {
  12. private:
  13. string duty;
  14. public:
  15. void showInfo() const {
  16. cout << Student::getName() << endl;
  17. cout << Student::getId() << endl;
  18. cout << duty << endl;
  19. }
  20. };

这样我们对Student对象和Cadre的对象分别调用showInfo的时候就会输出不同的结果.

但是这样会产生一个问题:

  1. Cadre *pc = new Cadre(1, "J", "monitor");
  2. Student &rc = *pc;
  3. pc->showInfo();
  4. cout << endl;
  5. rc.showInfo();
  6. /*output: J 1 monitor J 1*/

同一个Cadre对象, 用它自己的指针调用和用Student的引用调用时结果不一样. 查看输出结果可以知道用Student的引用调用的时候运行的是Student::showInfo, 而非在Cadre中重写的方法.

Virtual methods

为了让base-class引用的derived-class可以调用derived-class重写的方法, 我们可以使用virtual.

  1. class Student {
  2. public:
  3. ...
  4. virtual void showInfo() const {
  5. cout << name << "\t" << id;
  6. }
  7. };
  8. class Cadre : public Student {
  9. public:
  10. ...
  11. virtual void showInfo() const {
  12. Student::showInfo();//reusing code
  13. cout << "\t" << duty;
  14. }
  15. };

再来看看输出结果:

  1. Cadre *pc = new Cadre(1, "J", "monitor");
  2. Student &rc = *pc;//Student reference
  3. pc->showInfo();
  4. cout << endl;
  5. rc.showInfo();//invoke Cadre::showInfo() instead of Student::showInfo()
  6. /*output: J 1 monitor J 1 monitor */

如果不使用virtual, 调用的方法取决于引用或者指针的类型; 使用, 则由引用或者指向的对象本身决定, 也就是说可以使用base-class的引用或者指针调用在derived-class的重写的方法.

当base-class中的方法被标记为virtual时, derived-class中重写的方法也被自动标记为virtual. 不过一般为了方便阅读, 也将derived-class中重写的方法标记为virtual.

对于base-class中在derived-class被重写的方法一般都会被标记为virtual. 另外有derived-class的base-class的destructors最好被标记为virtual.

  1. class A {
  2. private:
  3. string *a;
  4. public:
  5. A() { a = new string("Hello"); }
  6. ~A() { delete a; }
  7. };
  8. class B : public A {
  9. private:
  10. string *b;
  11. public:
  12. B() : A() { b = new string("world"); }
  13. ~B() { delete b; }
  14. };
  15. int main() {
  16. A *pb = new B();
  17. delete pb;
  18. }

delete pb时会直接调用A::~A(), B中b的内存没有成功被释放. 所以为了内存的正确释放最好把base-class的destructor标记为virtual.

Static and Dynamic Binding

绑定是指调用哪个具体的方法. 例如上面不加virtual关键词时rc.showInfo会调用引用类型的showInfo, 即Student::showInfo; 而加上virtual会调用Cadre::showInfo.

  1. Cadre *pc = new Cadre(1, "J", "monitor");
  2. Student &rc = *pc;//Student reference
  3. rc.showInfo();

static binding是指在编译的时候就决定了调用的方法, 而dynamic binding是在程序运行过程中才能决定(因为对于一个base-class的指针可能指向base-class也可能指向derived-class). 这种dynamic binding的特性被称为多态.

c++默认的绑定方式是static binding. 对于dynamic binding对象内部会增加一个virtual function table (vtbl), 它负责记录这个对象应该调用的方法. 尽管dynamic binding看上去有更多的好处, 然而c++默认的绑定方式是static binding, 这样程序的运行效率更高. 与之对比, java中没有virtual function, 它默认的就是动态绑定.

dynamic binding产生的多态有什么好处呢? 看下面这个例子:

  1. class Class {
  2. private:
  3. vector<Student *> students;
  4. public:
  5. void addStudent(Student *student) {
  6. students.push_back(student);
  7. }
  8. void listStudent() {
  9. for (auto &s: students) {
  10. s->showInfo();
  11. cout << endl;
  12. }
  13. }
  14. };
  15. //
  16. Class cla;
  17. Student a = Student(1, "Y");
  18. Cadre b = Cadre(2, "Z", "monitor");
  19. Student c = Student(3, "W");
  20. cla.addStudent(&a);
  21. cla.addStudent(&b);
  22. cla.addStudent(&c);
  23. cla.listStudent();
  24. /*output Y 1 Z 2 monitor W 3 */

在Class中我们全都储存的是Student的指针, 在打印Student List的时候就可以根据指向的具体对象输出相应的信息.

Code

完整演示代码:

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. class Student {
  5. private:
  6. int id;
  7. string name;
  8. public:
  9. Student(int id, const string &name) : id(id), name(name) { }
  10. int getId() const { return id; }
  11. void setId(int id) { Student::id = id; }
  12. const string &getName() const { return name; }
  13. void setName(const string &name) { Student::name = name; }
  14. virtual void showInfo() const {
  15. cout << name << "\t" << id;
  16. }
  17. virtual ~Student() { }
  18. };
  19. class Cadre : public Student {
  20. private:
  21. string duty;
  22. public:
  23. Cadre(int id, const string &name, const string &duty) : duty(duty), Student(id, name) { }
  24. const string &getDuty() const { return duty; }
  25. void setDuty(const string &duty) { Cadre::duty = duty; }
  26. virtual void showInfo() const {
  27. Student::showInfo();
  28. cout << "\t" << duty;
  29. }
  30. };
  31. class Class {
  32. private:
  33. vector<Student *> students;
  34. public:
  35. void addStudent(Student *student) {
  36. students.push_back(student);
  37. }
  38. void listStudent() {
  39. for (auto &s: students) {
  40. s->showInfo();
  41. cout << endl;
  42. }
  43. }
  44. };
  45. int main() {
  46. Cadre *pc = new Cadre(1, "J", "monitor");
  47. Student &rc = *pc;
  48. pc->showInfo();
  49. cout << endl;
  50. rc.showInfo();
  51. delete pc;
  52. cout << endl;
  53. Class cla;
  54. Student a = Student(1, "Y");
  55. Cadre b = Cadre(2, "Z", "monitor");
  56. Student c = Student(3, "W");
  57. cla.addStudent(&a);
  58. cla.addStudent(&b);
  59. cla.addStudent(&c);
  60. cla.listStudent();
  61. return 0;
  62. }

懒惰的我终于又开始更新了.

发表评论

表情:
评论列表 (有 0 条评论,222人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++ 动态

    C++中动态绑定 定义 c++中动态绑定是将一个过程调用与相应代码链接起来的行为。是指与给定的过程调用相关联的代码,只有在运行期才可知的一种绑定,他是[多态][Li

    相关 C++动态和静态

    为了支持c++的多态性,才用了动态绑定和静态绑定。理解他们的区别有助于更好的理解多态性,以及在编程的过程中避免犯错误。 需要理解四个名词: 1、对象的静态类型:对象在