这里我们说说多重继承(multiple inheritance)。 多重继承的问题涉及到建构子和析构子的调用顺序问题, 多重继承造成的歧义型(例如, 当多个base classes中有同名函数的时候, 如何解决, members from common base class如何解决(dimond的时候, 即类A继承自B, C, 但是B, C又同时继承自一个类D时候, 就出现歧义了, 此时A有两份关于D的拷贝))。 当涉及到vitual base class(虚基类)的时候, 初始化的顺序和调用顺序如何呢??
首先, 定义一个class具有多个parent class 很简单, 只需要list them one by one:
<span style="font-size:14px;">class Boo: public Bum, public Foo {
// specify its own properties
};</span>
这样, 一个Boo类的object可以upcast(向上转型)为 Bum, 或者Foo, 因为Boo继承了其父类的一切, 虽然object无法看到父类的private的部分。
当我们创建一个Boo的object的时候, 需要先调用Bum 和 Foo的default constructor, 然后在调用自己的。 也就是说, 先构造父亲的那一部分, 调用析构子的顺序和调用构造子的顺序相反。
如下:
#include <iostream>
using namespace std;
class Sofa {
public:
Sofa() {
cout << "构造Sofa" << endl;
}
~Sofa() {
cout << "析构Sofa" << endl;
}
void sit() {
cout << "sit" << endl;
}
};
class Bed {
public:
Bed() {
cout << "构造Bed" << endl;
}
~Bed() {
cout << "析构Bed" << endl;
}
void lie() {
cout << "lie" << endl;
}
};
class Sofabed: public Bed, public Sofa { //按照list的顺序构建, 即继承的顺序
public:
Sofabed() {
cout << "构造Sofabed" << endl;
}
~Sofabed() {
cout &l