c++ vitual继承
为了解决多继承下的二义性而设计的vitrul继承
class Base { public: Base(void); ~Base(void); }; Base::Base(void) { printf("Base::Base():%p\n",this); } class ChildFirst : /*vitual*/ public Base { public: ChildFirst(void); ~ChildFirst(void); }; ChildFirst::ChildFirst(void) { printf("ChildFirst::ChildFirst()\n"); } class ChildSencond : /* vitrual */public Base { public: ChildSencond(void); ~ChildSencond(void); }; ChildSencond::ChildSencond(void) { printf("ChildSencond::ChildSencond()\n"); } class GrandChild :public ChildFirst, ChildSencond { public: GrandChild(void); ~GrandChild(void); }; GrandChild::GrandChild(void) { printf("GrandChild::GrandChild()\n"); } int _tmain(int argc, _TCHAR* argv[]) { GrandChild grandChild; return 0; }
这样的话,Base::()Base()会被调用两次而且两次地址不同。
输出
Base::Base():0x0015ff0f
ChildFirst::ChildFirst()
Base::Base():0x0015ff10
ChildSecond::ChildSecond()
GrandChild::GrandChild()
.为解决上述问题,请把注释了virtual打开,注意写法,vitual是直接继承的那里写的。
打开后的输出为:
Base::Base():0x0015000f
ChildFirst::ChildFirst()
ChildSecond::ChildSecond()
GrandChild::GrandChild()