1. 概述
C++虚继承的作用:避免多重继承时因基类的重复而引起的调用二义性.
2. 多重继承 + 非虚继承
#define MemoryLayout_H #ifdef MemoryLayout_H class Base { public: void CommonFunction(); virtual void VirtualFunction1(); virtual void VirtualFunction2(); private: int m_baseVar1; int m_baseVar2; }; //class Derived1:virtual public Base class Derived1 :public Base { public : void Derived1CommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void Derived1VirtualFunction(); private: int m_derived1Var; }; //class Derived2 :virtual public Base class Derived2 :public Base { public: void Derived2CommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void Derived2VirtualFunction(); private: int m_derived2Var; }; class DerivedDerived :public Derived1,public Derived2 { public: void DerivedCommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void DerivedDerivedVirtualFunction(); private: int m_derivedDerivedVar; }; #endif/*MemoryLayout_H*/
利用vs2015输出其内存布局分别为:
Base:
Derived1:
Derived2:
DerivedDerived:
内存布局分析:
这里主要分析DerivedDerived类的内存布局:
此继承关系中,若通过DD类实例调用VF1函数,会产生歧义.
3. 多重继承+虚继承
#define MemoryLayout_H #ifdef MemoryLayout_H class Base { public: void CommonFunction(); virtual void VirtualFunction1(); virtual void VirtualFunction2(); private: int m_baseVar1; int m_baseVar2; }; class Derived1:virtual public Base //class Derived1 :public Base { public : void Derived1CommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void Derived1VirtualFunction(); private: int m_derived1Var; }; class Derived2 :virtual public Base //class Derived2 :public Base { public: void Derived2CommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void Derived2VirtualFunction(); private: int m_derived2Var; }; class DerivedDerived :public Derived1,public Derived2 { public: void DerivedCommonFunction(); //virtual void VirtualFunction1(); virtual void VirtualFunction2(); virtual void DerivedDerivedVirtualFunction(); private: int m_derivedDerivedVar; }; #endif/*MemoryLayout_H*/
利用vs2015输出其内存布局分别为:
Base:
Base类的内存布局与非虚继承时相同.
Derived1:
Derived1内存布局分析:
Derived2:
Derived2内存布局与Derived1相同.
DerivedDerived:
DerivedDerived内存布局分析:
这里是否缺少一个信息,若通过指针调用Derived2的DerivedDerivedVirtualFunction函数,应该怎么处理?没有展示出来.