首页  

c++菱形继承     所属分类 c 浏览量 740
菱形继承是多继承的一种特殊情况
造成数据冗余和二义性问题
解决办法  菱形虚拟继承
不建议设计多继承,一定不要设计菱形继承

#include "iostream"
using namespace std;
class A{
  public:
    int a;
};

class B:public A{
  public:
    int b;
};

class C:public A{
  public:
    int c;
};

class D:public B,public C{
  public:
    int d;
};

///



class B1:virtual public A{
  public:
    int b;
};

class C1:virtual public A{
  public:
    int c;
};

class D1:public B1,public C1{
  public:
    int d;
};
///

int main(){
  
  cout << "sizeof(A) " << sizeof(A) << endl;
  cout << "sizeof(B) " << sizeof(B) << endl;
  cout << "sizeof(C) " << sizeof(C) << endl;
  cout << "sizeof(D) " << sizeof(D) << endl;
  D d;
  d.B::a=1;
  d.C::a=2;
  // d.a = 3;
  
  // use virtual
  cout << "sizeof(B1) " << sizeof(B1) << endl;
  cout << "sizeof(C1) " << sizeof(C1) << endl;
  cout << "sizeof(D1) " << sizeof(D1) << endl;
  
  
  D1 d1;
  d1.B1::a=1;
  d1.C1::a=2;
  d1.a = 3;
}


d.a = 3; 编译报错
error: non-static member 'a' found in multiple base-class subobjects of type 'A':
    class D -> class B -> class A
    class D -> class C -> class A
  d.a = 3;

B1 C1 继承 A时 加上 virtual

B1 C1 添加额外的指针
虚基表指针  
偏移量表/虚基表

上一篇     下一篇
C++11 lambda

编程的十个至理名言

c++异常处理

c++ 虚函数多态

几个有趣的C语言面试题及答案

c 指针数组