gem456 发表于 2016-4-20 23:36:40

继承和派生的代码出现了一点问题。。。。

派生一个摩托车类时,在构造函数中写上motorcycle(float m, float w, float h, int s): bicycle(m, w, h),motorcar(m, w, s)//在此句后面加上float(w,m) 然后会报错
error C2614: 'motorcycle' : illegal member initialization: 'vehicle' is not a base or member
#include<iostream>
using namespace std;
class vehicle
{
public:
        vehicle(float w,float m)    //创建一个vehicle类
        {
                weight=w;
                maxspeed=m;
                cout<<"这辆车的最大速度为:"<<maxspeed<<endl;
                cout<<"这辆车的重量为:"<<weight<<endl;

        }
        run();
        stop();
private:float weight, maxspeed;
};
vehicle::run()                  //vehicle的成员函数
{
        cout<<"车已启动。。。。。。"<<endl;
}
vehicle::stop()                //vehicle的成员函数

{
        cout<<"车已停了!"<<endl;
}
class bicycle:publicvehicle//创造一个单车类
{
public:
        bicycle(float w,float m,float h):vehicle(w,m)
        {
                height=h;
                cout<<"这辆车的高度为:"<<height<<endl;
        }
private:float height;
};

class motorcar:publicvehicle //创造一个汽车类
{
public:
        motorcar(float w,float m,int s):vehicle(w,m)
        {
                seatnum=s;
                cout<<"这辆车能载的人数为:"<<seatnum<<endl;
        }
private:int seatnum;
};

class motorcycle: public bicycle, public motorcar//创造一个摩托车类。。。
{
public:
motorcycle(float m, float w, float h, int s): bicycle(m, w, h),motorcar(m, w, s)//在此句后面加上float(w,m) 然后会报错
{ }
};

int main()
{   
        motorcar car(100,150,7);
        car.run();
        car.stop();
        bicycle cle(15,10,1.20);
        cle.run();
        cle.stop();
        motorcycle cycle(50,100,2,1);
       
        return 0;
}
这是我在写程序上遇到的问题,想问问这是什么原因。。。。。。。。。。。。。

n0noper 发表于 2016-4-21 09:38:17

卤煮,vehicle不是你的父类,你并不知道他跟你有关系,所以不能再motorcycle构造函数中初始化vehicle。

隔一层时透明的啊! 你继承谁就认识谁。你只需要关心你直接相关的上一层就可以了。

页: [1]
查看完整版本: 继承和派生的代码出现了一点问题。。。。