C++ 课程作业 继承与派生 (motorcycle类设计(虚基类))

首先是题目
【问题描述】
声名一个基类vehicle,有私有成员maxspeed和weight,公有成员run()和stop(),以及构造和析构函数。
从vehicle派生bicycle和motorcar, bicycle有私有成员height, motorcar有私有成员seatnum,以及各自的构造函数和析构函数。
从bicycle和motorcar派生出motorcycle,观察虚基类对继承的影响。
定义一个motorcycle的对象,分别调用run()和stop(),观察构造/析构函数的调用情况。
注意:构造函数和析构函数中均为cout语句,说明哪个构造/析构函数被调用。
该题重点和难点在于构造函数的设计,需考虑怎么给基类及最远基类传递参数。

然后是代码

#include 
using namespace std;
class vehicle
{
    int maxspeed, weight;
public:
    void run() { cout << "vehicle run" << endl; }
    void stop() { cout << "vehicle stop" << endl; }
    vehicle(int speed = 0, int wei = 0) { maxspeed = speed; weight = wei; cout << "vehicle constructor called. maxspeed:" << maxspeed << "; weight" << weight << endl; }//先设置默认参数,防止后面无法调用构造函数
    ~vehicle(){ cout<<"vehicle destructor called. maxspeed:" << maxspeed << "; weight" << weight << endl; }
};
class bicycle :virtual public vehicle//虚基类的定义在第一层派生类,不然会出错,系统会不知道调用哪个构造函数
{
    int height;
public:
    ~bicycle() { cout << "bicycle destructor called. height:" << height << endl; }
    bicycle(int speed, int wei, int hei) :vehicle(speed, wei), height(hei) { cout << "bicycle constructor called. height:" << height << endl; }//初始化本类参数和基类参数(基类必须要初始化)
};
class motorcar :virtual public vehicle//同样是第一层派生类
{
    int seatnum;
public:
    motorcar(int speed, int wei, int seat) :vehicle(speed, wei), seatnum(seat) { cout << "motorcar constructor called. seatnum:" << seatnum << endl; }
    ~motorcar() { cout << "motorcar destructor called. seatnum:" << seatnum << endl; }
};
class motorcycle : public bicycle,  public motorcar//第二层派生类,最后一层,不需要virtual
{=
public:
    motorcycle(int hei, int seat, int speed, int wei) :vehicle(speed, wei), bicycle(speed, wei, hei), motorcar(speed, wei, seat) { cout << "motorcycle constructor called" << endl; }//所有一脉相承的类都需要初始化参数!!
    ~motorcycle() { cout << "motorcycle destructor called" << endl; }
};
int  main(int  argc, char* argv[])
{
    motorcycle  m(1, 2, 3, 4);//1表示height,2表示setnum,3表示maxspeed,4表示weight
    m.run();
    m.stop();
    return  0;
}

总结:虚基类virtual的位置不是在最后一层派生类的定义上(因为第一次是这么写的,然后就出问题了)
每个类的初始化都要包括上一层类的初始化。

你可能感兴趣的:(C++ 课程作业 继承与派生 (motorcycle类设计(虚基类)))