在多重继承中,要引用派生类的成员时,先是在派生类自身的作用域内寻找,如果找不到再到基类中寻找。这时,如果这些基类有一个共同的基类,派生类访问这个共同基类的成员时,就有可能由于同名成员的问题发生二义性,此时就需要用虚基类来解决这个问题。例如:
#include<iostream> using namespace std; class Base { protected: int x; public: Base() { x=1; } }; class Base1:public Base { public: Base1() { cout<<"Constructing Base1, x= "<<x<<endl; } }; class Base2:public Base { public: Base2() { cout<<"Constructing Base2, x= "<<x<<endl; } }; class Derived:public Base1,public Base2 { public: Derived() { cout<<"Constructing Derived x"<<x<<endl; } }; int main() { Derived obj; system("pause"); }
图1:非虚基类的类层次结构
#include<iostream> using namespace std; class Base { protected: int x; public: Base() { x=1; } }; class Base1:virtual public Base//virtual { public: Base1() { cout<<"Constructing Base1, x= "<<x<<endl; } }; class Base2:virtual public Base//virtual { public: Base2() { cout<<"Constructing Base2, x= "<<x<<endl; } }; class Derived:public Base1,public Base2 { public: Derived() { cout<<"Constructing Derived x= "<<x<<endl; } }; int main() { Derived obj; system("pause"); }