1. 虚继承的引入(解决访问二义性)
class A
{
public:
int m_a;
};
class B:public A
{
public:
};
class C :public A
{
public:
};
class D :public B, public C
{
public:
};
int main()
{
D d;
d.m_a = 5; //error
return 0;
}
解决:
class A
{
public:
int m_a;
};
class B:virtual public A
{
public:
int m_b;
};
class C :virtual public A
{
public:
int m_c;
};
class D :public B, public C
{
public:
int m_d;
};
2. 两层结构
class A
{
public:
int m_a;
};
class B:virtual public A
{
public:
int m_b;
};
class A1
{
public:
int m_a1;
};
class A2
{
public:
int m_a2;
};
class B:virtual public A1, public A2
{
public:
int m_b;
};
class A1
{
public:
int m_a1;
};
class A2
{
public:
int m_a2;
};
class B:virtual public A1, virtual public A2
{
public:
int m_b;
};
3. 三层结构
class A
{
public:
int m_a;
};
class B:virtual public A
{
public:
int m_b;
};
class C :virtual public A
{
public:
int m_c;
};
class D :public B, public C
{
public:
int m_d;
};
int main()
{
cout << sizeof(A) << endl;
cout << sizeof(B) << endl;
cout << sizeof(C) << endl;
cout << sizeof(D) << endl;
D d;
d.m_a = 1;
d.m_b = 2;
d.m_c = 3;
d.m_d = 4;
return 0;
}
现在执行 d.m_a = 4;首先通过第一个vbptr指向的虚基类表中取出第二项,得到偏移为 20,然后向下移动20个字节得到 m_a存储的位置,所以访问虚基类的成员变量要比访问一般的成员变量慢。