申明:本文主要参考MSDN
虚继承:在继承定义中包含了virtual关键字的继承关系;
虚基类:在虚继承体系中的通过virtual继承而来的基类;
声明虚基类的一般形式为
class 派生类名: virtual 继承方式 基类名
需要注意: 为了保证虚基类在派生类中只继承一次,应当在该基类的所有直接派生类中声明为虚基类。否则仍然会出现对基类的多次继承。
将类A声明为虚基类,方法如下:
class A//声明基类A
{…};
class B :virtual public A//声明类B是类A的公用派生类,A是B的虚基类
{…};
class C :virtual public A//声明类C是类A的公用派生类,A是C的虚基类
{…};
虚继承 Demo 参考来自:http://www.cnblogs.com/itech/archive/2009/03/01/1399996.html
#include <iostream>
using namespace std;
class B
{
public:
int i;
virtual void vB(){ cout << "B::vB" << endl; }
void fB(){ cout << "B::fB" << endl;}
};
class D1 : virtual public B
{
public:
int x;
virtual void vD1(){ cout << "D1::vD1" << endl; }
void fD1(){ cout << "D1::fD1" << endl;}
};
class D2 : virtual public B
{
public:
int y;
void vB(){ cout << "D2::vB" << endl;}
virtual void vD2(){ cout << "D2::vD2" << endl;}
void fD2(){ cout << "D2::fD2" << endl;}
};
class GD : public D1, public D2
{
public:
int a;
void vB(){ cout << "GD::vB" << endl;}
void vD1(){cout << "GD::vD1" << endl;}
virtual void vGD(){cout << "GD::vGD" << endl;}
void fGD(){cout << "GD::fGD" << endl;}
};
虚基类: 用于某类从多个类继承,这多个基类有共同基类时,这个最上层基类的成员会多次在最终派生类出现而产生二义性,为避免二义性,使得最终派生类中,最上层的基类成员只有一份,这时需要虚拟继承,该最上层类就是虚基类,需要注意的是,该类在第一层派生时就要虚拟继承才行,使用方法是在继承方式前加上一个 virtual就可以了
#include <iostream>
using namespace std;
class CBase
{
protected:
int a;
public:
CBase(int na)
{
a = na;
cout << "CBase constructor" << endl;
}
~CBase()
{
cout << "CBase deconstructor!" << endl;
}
};
class CDerive1: virtual public CBase
{
public:
CDerive1(int na) : CBase(na)
{
cout << "CDerive1 constructor" << endl;
}
~CDerive1()
{
cout << "CDerive1 deconstructor" << endl;
}
int GetA()
{
return a;
}
};
class CDerive2: virtual public CBase
{
public:
CDerive2(int na): CBase(na)
{
cout << "CDerive2 constructor" << endl;
}
~CDerive2()
{
cout << "CDerive2 deconstructor" << endl;
}
int GetA()
{
return a;
}
};
class CDerive12: public CDerive1,public CDerive2
{
public:
CDerive12(int na1,int na2,int na3): CDerive1(na1), CDerive2(na2), CBase(na3)
{
cout << "CDerive12 constructor" << endl;
}
~CDerive12()
{
cout << "CDerive12 deconstructor" << endl;
}
};
void main()
{
CDerive12 obj(100,200,300);
cout << "frome CDerive1: a = " << obj.CDerive1::GetA() << endl;
cout << "frome CDerive2: a = " << obj.CDerive2::GetA() << endl << endl;
system("pause");
}
效果: