m0_52459437
m0_52459437
采纳率0%
2021-03-07 17:14

c++虚基类有关的参数传递出现了问题,出问题处已经备注,大神们可怜可怜孩子

#include <iostream>
using namespace std;
/*
定义一个车(vehicle)基类,具有MaxSpeed、Weight等成员变量,Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类。
自行车(bicycle)类有高度(Height)等属性,汽车(motorcar)类有座位数(SeatNum)等属性。从bicycle和motorcar派生出摩托车(motorcycle)类。
请将vehicle设置为虚基类进行实验
输出:::::
vehicle is running...
vehicle is stopped...
vehicle is running...
vehicle is stopped...
vehicle is running...
vehicle is stopped...
vehicle is running...
vehicle is stopped...
*/
class vehicle///虚基类vehicle
{
    public:
    vehicle(float maxspeed,float weight):MaxSpeed(maxspeed),Weight(weight){}
    vehicle(){}
    void Run();
    void Stop();
    private:
    float MaxSpeed,Weight;
};
void vehicle::Run()
{
    cout<<"vehicle is running..."<<endl;
}
void vehicle::Stop()
{
    cout<<"vehicle is stopped..."<<endl;
}
class bicycle:virtual public vehicle///////bicycle继承vehicle
{
    float Height;
public:
    bicycle(float height,float maxspeed,float weight):vehicle(maxspeed,weight),Height(height){}
    bicycle(){}
};
class motorcar:virtual public vehicle////motorcar继承vehicle
{
    int SeatNum;
public:
    motorcar(int seatnum,float maxspeed,float weight):vehicle(maxspeed,weight),SeatNum(seatnum){}
    motorcar(){}
};
class motorcycle:public bicycle, public motorcar//////motorcycle继承bicycle和motorcycle
{
    public:

        motorcycle(float height, int seatnum, float maxspeed, float weight): bicycle(height), motorcar(seatnum),vehicle(maxspeed,weight){}
        ///此处报错此处报错此处报错此处报错此处报错此处报错此处此处报错此处报错此处报错
    //////////////////报错此处报错此处报错bicycle(height), motorcar(seatnum),此处报错,不知道为什么
        motorcycle(){}

};

void fun(vehicle *p)
{
    p->Run();
    p->Stop();
}
int main()
{
    vehicle v;
    bicycle by;
    motorcar mc;
    motorcycle mcy;
    fun(&v);
    fun(&by);
    fun(&mc);
    fun(&mcy);
    system("pause"); 
    return 0;
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • huanhuilong 幻灰龙 1月前

    类 `motorcar` 提供了两个构造函数

    • motorcar(int seatnum,float maxspeed,float weight):vehicle(maxspeed,weight),SeatNum(seatnum){}
    • motorcar(){}

    但是你继承的时候,提供给 motorcar 的参数个数只有1个?上述两个构造函数,一个接受 3 个参数,一个没有参数,不匹配就报错了,其他同理:

    motorcycle(float height, int seatnum, float maxspeed, float weight)
    
    : bicycle(height), motorcar(seatnum), vehicle(maxspeed, weight) {}
    点赞 评论 复制链接分享

为你推荐