定义一个车类(vehicle)基类,有MaxSpeed、Weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类。自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)类有座位数(Seatnum)等属性。从bicycle和motorcar中派生出摩托车(motorcycle)类,在继承和过程中,注意把vehicle设置为虚基类。
注意观察下列构造函数的参数传递
#include<iostream>
using namespace std;
class vehicle
{
public:
vehicle(float m,float w):MaxSpeed(m),Weight(w){cout<<"vehicle constructor"<<endl;}
~vehicle(){cout<<"vehicle destructor"<<endl;}
protected:
float MaxSpeed; //最大速度
float Weight; //重量
};
class bicycle:virtual public vehicle //设置 vehicle为虚基类
{
public:
bicycle(float m,float w,float h):vehicle(m,w),Height(h){cout<<"bicycle constructor"<<endl;} //带有虚基类的派生类的构造函数,要对虚基类进行参数的传递
void Show()
{
cout<<"MaxSpeed:"<<MaxSpeed<<endl; //最大速度
cout<<"Weight:"<<Weight<<endl; //重量
cout<<"Height:"<<Height<<endl; //高度
}
~bicycle(){cout<<"bicycle destructor"<<endl;}
protected:
float Height;
};
class motorcar:virtual public vehicle
{
public:
motorcar(float m,float w,int s):vehicle(m,w),SeatNum(s){cout<<"motorcar constructor"<<endl;} //派生类参数传递
void Show()
{
cout<<"MaxSpeed:"<<MaxSpeed<<endl; //最大速度
cout<<"Weight:"<<Weight<<endl; //重量
cout<<"SeatNum:"<<SeatNum<<endl; //最大座位数
}
~motorcar(){cout<<"motorcar destructor"<<endl;}
protected:
int SeatNum;
};
class motorcycle:public bicycle,public motorcar
{
public:
motorcycle(int m,int w,int h,int s):vehicle(m,w),bicycle(m,w,h),motorcar(m,w,s){cout<<"motorcycle constructor"<<endl;} //最远的派生类,参数传递
//在声明motorcycle的对象时,虚基类的构造函数只调用这一次,两个直接基类的调用被忽略
void Show()
{
cout<<"MaxSpeed:"<<MaxSpeed<<endl; //最大速度
cout<<"Weight:"<<Weight<<endl; //重量
cout<<"Height:"<<Height<<endl; //高度
cout<<"SeatNum:"<<SeatNum<<endl; //最大座位数
}
~motorcycle(){cout<<"motorcycle destructor"<<endl;}
};
int main()
{
bicycle b(30,30,110); //直接基类bicycle
b.Show();
motorcar m(300,120,150); //直接基类motorcar
m.Show();
motorcycle mo(150,200,75,2); //派生类motorc
mo.Show();
return 0;
}
以下为派生类对象起作用时构造函数与析构函数的调用顺序
去掉virtual关键词后,出现下图所示错误: