虚继承主要是解决多继承时可能发生的对同一基类继承而产生的二义性问题。
#include<iostream>
using namespace std;
class A
{
public:
int m_n;
A(int n);
};
{
public:
int m_n;
A(int n);
};
A::A(int n)
{
m_n=n;
}
{
m_n=n;
}
class B:virtual public A
{
private:
int m_b;
public:
B(int n,int b);
};
{
private:
int m_b;
public:
B(int n,int b);
};
B::B(int n,int b) :A(n)
{
m_b=b;
}
{
m_b=b;
}
class C : virtual public A
{
private:
int m_c;
public:
C(int n,int c):A(n),m_c(c){}
};
class D : public B,public C
{
private:
int m_d;
public:
D(int n,int b,int c,int d):B(n,b),C(n,c),m_d(d),A(n){}
};
int main()
{
D d(1,2,3,4);
cout<<(d.m_n)<<endl;
return 0;
}
{
private:
int m_c;
public:
C(int n,int c):A(n),m_c(c){}
};
class D : public B,public C
{
private:
int m_d;
public:
D(int n,int b,int c,int d):B(n,b),C(n,c),m_d(d),A(n){}
};
int main()
{
D d(1,2,3,4);
cout<<(d.m_n)<<endl;
return 0;
}
使用虚继承,避免了数据成员的冗余复制,以上程序访问基类数据成员n,其实可以有以下四种方式: d.n; d.A::n; d.B::n; d.C::n;