以上面的代码为例,我们要想让AmphibianCar类既获得一个Vehicle的拷贝,而且又同时共享用Car类与Boat类的数据成员与成员函数就必须通过C++所提供的
虚拟继承技术来实现。
我们在Car类和Boat类继承Vehicle类出,在前面加上virtual关键字就可以实现虚拟继承,使用虚拟继承后,
当系统碰到多重继承的时候就会自动先加入一个Vehicle的拷贝,当再次请求一个Vehicle的拷贝的时候就会被忽略,保证继承类成员函数的唯一性。
修改后的代码如下,注意观察变化:
//程序作者:管宁
//站点:www.cndev-lab.com
//所有稿件均有版权,如要转载,请务必著名出处和作者
#include <
iostream>
usingnamespacestd;
classVehicle
{
public:
Vehicle(
intweight
=0)
{
Vehicle::weight
=weight;
cout<<"载入Vehicle类构造函数"<<ENDL;
}
voidSetWeight(
intweight)
{
cout<<"重新设置重量"<<ENDL;
Vehicle::weight
=weight;
}
virtualvoidShowMe()
=0;
protected:
intweight;
};
classCar:
virtualpublicVehicle
//汽车,这里是虚拟继承
{
public:
Car(
intweight=0,
intaird=0):Vehicle(weight)
{
Car::aird
=aird;
cout<<"载入Car类构造函数"<<ENDL;
}
voidShowMe()
{
cout<<"我是汽车!"<<ENDL;
}
protected:
intaird;
};
classBoat:
virtualpublicVehicle
//船,这里是虚拟继承
{
public:
Boat(
intweight=0,
floattonnage=0):Vehicle(weight)
{
Boat::tonnage
=tonnage;
cout<<"载入Boat类构造函数"<<ENDL;
}
voidShowMe()
{
cout<<"我是船!"<<ENDL;
}
protected:
floattonnage;
};
classAmphibianCar:
publicCar,
publicBoat
//水陆两用汽车,多重继承的体现
{
public:
AmphibianCar(
intweight,
intaird,
floattonnage)
:Vehicle(weight),Car(weight,aird),Boat(weight,tonnage)
//多重继承要注意调用基类构造函数
{
cout<<"载入AmphibianCar类构造函数"<<ENDL;
}
voidShowMe()
{
cout<<"我是水陆两用汽车!"<<ENDL;
}
voidShowMembers()
{
cout<<"重量:"<<WEIGHT<<"顿,"<<"空气排量:"<<AIRD<<"CC,"<<"排水量:"<<TONNAGE<<"顿"<<ENDL;
}
};
intmain()
{
AmphibianCar a(4,200,1.35f);
a.ShowMe();
a.ShowMembers();
a.SetWeight(3);
a.ShowMembers();
system("pause");
}
注意观察类构造函数的构造顺序。
虽然说虚拟继承与虚函数有一定相似的地方,但读者务必要记住,他们之间是绝对没有任何联系的!