gpt4 book ai didi

c++ - 如何使用继承定义父类的函数?

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:29 25 4
gpt4 key购买 nike

我已经公开了父类的成员函数。但是还是报错

no 'void MotorBike::speeddown()' member function declared in class 'MotorBike'

speedupspeeddown。尽管我已经公开继承了父类。

#include <iostream>
#include<string.h>
using namespace std;

class Bicycle
{
protected:
int speed;
char color[8];
public:
Bicycle(int, char*);
void speedup();
void speeddown();
void turnLeft();
void turnRight();
};

class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
MotorBike(int,char*,int,int);

};

Bicycle::Bicycle(int Speed,char* Color)
{
speed=Speed;
strcpy(color,Color);
cout<<"The bike is now moving north!"<<endl;
}

MotorBike::MotorBike(int Speed,char* Color,int CurrentGear,int CurrentFuel): Bicycle(speed,color)
{
speed=Speed;
strcpy(color,Color);
currentGear=CurrentGear;
currentFuel=CurrentFuel;
cout<<"The motorbike is now moving north!"<<endl;
}

void Bicycle::speedup()//error line
{
cout<<"Speed is increased!"<<endl;
speed+=1;
}

void Bicycle::speeddown()//error line
{
if(speed>1)
{
cout<<"Speed is decreased!"<<endl;
speed-=1;
}
else
cout<<"The bike is already at rest!"<<endl;

}

void MotorBike::speedup()//error line
{
if(currentGear==4)
cout<<"You are already at maximum speed!"<<endl;
else
{
switch(currentGear)
{
case 0:
currentGear=1;
currentFuel-=0.01;
speed+=0.25;
break;
case 1:
currentGear=2;
currentFuel-=0.02;
speed+=0.5;
break;
case 2:
currentGear=3;
currentFuel-=0.03;
speed+=0.75;
break;
case 3:
currentGear=4;
currentFuel-=0.04;
speed+=1;
break;

}
}
}

void MotorBike::speeddown()//error line
{
if(speed==1||speed>1)
speed-=1;
else
cout<<"You are already at minimum speed!"<<endl;
}

int main()
{
Bicycle B1(0,"Black");
MotorBike MB1(0,"Black",0,100);
}

最佳答案

您的MotorBike 没有函数speedupspeeddown。如果你想要,你必须在 MotorBike 类中声明它,比如

class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
MotorBike(int,char*,int,int);
void speedup();
void speeddown();
};

关于c++ - 如何使用继承定义父类的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37446478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com