举个例子,交通工具类可以派生出汽车和船连个子类,但拥有汽车和船共同特性水陆两用汽车就必须继承来自汽车类与船类的共同属性。
由此我们不难想出如下的图例与代码:
当一个派生类要使用多重继承的时候,必须在派生类名和冒号之后列出所有基类的类名,并用逗好分隔。
//程序作者:管宁
//站点:www.cndev-lab.com
//所有稿件均有版权,如要转载,请务必著名出处和作者
#include <iostream>
using namespace std;
class Vehicle
{
public:
Vehicle(int weight = 0)
{
Vehicle::weight = weight;
}
void SetWeight(int weight)
{
cout<<"重新设置重量"<<endl;
Vehicle::weight = weight;
}
virtual void ShowMe() = 0;
protected:
int weight;
};
class Car:public Vehicle//汽车
{
public:
Car(int weight=0,int aird=0):Vehicle(weight)
{
Car::aird = aird;
}
void ShowMe()
{
cout<<"我是汽车!"<<endl;
}
protected:
int aird;
};
class Boat:public Vehicle//船
{
public:
Boat(int weight=0,float tonnage=0):Vehicle(weight)
{
Boat::tonnage = tonnage;
}
void ShowMe()
{
cout<<"我是船!"<<endl;
}
protected:
float tonnage;
};
class AmphibianCar:public Car,public Boat//水陆两用汽车,多重继承的体现
{
public:
AmphibianCar(int weight,int aird,float tonnage)
:Vehicle(weight),Car(weight,aird),Boat(weight,tonnage)
//多重继承要注意调用基类构造函数
{
}
void ShowMe()
{
cout<<"我是水陆两用汽车!"<<endl;
}
};
int main()
{
AmphibianCar a(4,200,1.35f);//错误
a.SetWeight(3);//错误
system("pause");
}