Virtual Inheritance
C++ primer:
Virtual Inheritance:
A base class is specified as being derived through virtual inheritance by modifying its declaration with the keyword virtual.
个人修正:
A base class is specified as being derived through virtual inheritance by modifying all of its declarations with the keyword virtual.
Virtual base classes are always constructed prior to non-virtual base classes regardless of where they appear in inheritance hierarchy.
例1、并未实现虚继承
class Base1 {
public:
Base1(void) {
cout << "class Base1" << endl;
}
void fun() { cout << "Base1's function " <<endl;}
};
class Base2 {
public:
Base2(void) {
cout << "class Base2" << endl;
}
};
class Level1:virtual public Base2, public Base1 {
public:
Level1(void) {
cout << "class Level1" << endl;
}
};
class Level2:public Base2,virtual public Base1 {
public:
Level2(void) {
cout << "class Level2" << endl;
}
};
class Leaf:public Level1,virtual public Level2 {
public:
Leaf(void) {
cout << "class Leaf" << endl;
}
};
int main()
{
Leaf L1;
L1.fun();
system("pause");
return 0;
}
编译器按照直接基类在声明中的顺序,来检查虚拟基类的出现情况。在我们的例子中,Level1首先被检查,然后是Level2。每个继承子树按照深度优先的顺序被检查。即,查找从树根类开始,然后向下移动。如对子树Level1而言,先检查Base2,然后是Base1,再到Level1。但是在虚拟继承中,基类构造函数的查找顺序只是为了知道虚拟继承的情况而已,基类构造函数的调用顺序和查找顺序是不一样的,那应该遵循什么样的一个原则呢?
遵循两个原则,而且按顺序优先满足:
1先调用虚拟基类,再调用非虚拟基类。
2先调用完所以基类,再调用子类;
一旦调用了虚拟基类的构造函数,则非虚拟基类构造函数就按照声明的顺序被调用。
所以针对我们这个例子,因为声明类Leaf的顺序是先Level1后Level2,所以先看看Level1这棵子树吧。
由于Level1虚拟继承Base2,非虚拟继承Base1,所以应该先调用Base2,但是这之后不能接着调用Level1这棵子树的Base1,因为其他子树还有虚拟继承。
现在来看看Level2这棵子树吧,由于Level2虚拟继承Base1,非虚拟继承Base2,所以先调用Base1,后Base2。既然Level2的两个基类都调用了,并且Level2也是一个虚拟基类,所以现在应该调用Level2的构造函数了。
这样,Level2这棵子树的构造函数都调用完了,又回到Level1这棵子树了。接着刚才,由于Level1的Base2已经调用了,接着应该调用Base1了,之后是Level1。
当Leaf的所有直接和间接的基类都调用之后,最后是Leaf构造函数了。
经过以上分析,大家应该知道构造函数的调用顺序了吧,所以该程序的输出应该是
注意:若将main函数中的L1.fun();语句打开,将出现编译错误:
error C2385: 'Leaf::fun' is ambiguous
warning C4385: could be the 'fun' in base 'Base1' of base 'Level1'of class 'Leaf'
例2、实现虚继承
将程序修改为:
class Base1 {
public:
Base1(void) {
cout << "class Base1" << endl;
}
void fun() { cout << "Base1's function " <<endl;}
};
class Base2 {
public:
Base2(void) {
cout << "class Base2" << endl;
}
};
class Level1:virtual public Base2, virtual public Base1 {
public:
Level1(void) {
cout << "class Level1" << endl;
}
};
class Level2:virtual public Base2,virtual public Base1 {
public:
Level2(void) {
cout << "class Level2" << endl;
}
};
class Leaf:public Level1,virtual public Level2 {
public:
Leaf(void) {
cout << "class Leaf" << endl;
}
};
int main()
{
Leaf L1;
L1.fun();
system("pause");
return 0;
}
输出:
可以看到,Base1和Base2的构造函数只被调用了一次。
因为:Base1和Base2的所有派生类在继承Base1和Base2的时候都使用了虚继承,这样才能实现Virtual Inheritance。
http://blog.csdn.net/bigsnowstorm/article/details/8810167