我已将父类的成员函数设为public。但我仍然收到错误
no' void MotorBike :: speeddown()'在课程' MotorBike'
中声明的成员函数
speedup
和speeddown
。即使我公开继承了父类。
#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);
}
答案 0 :(得分:0)
您的speedup
没有功能speeddown
或MotorBike
。如果你想要,你必须在class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
MotorBike(int,char*,int,int);
void speedup();
void speeddown();
};
类中声明它,比如
rowattr
答案 1 :(得分:-1)
我将在这个问题上自上而下:
将已弃用的#include <string.h>
更改为#include <string>
。
你的自行车具有无定义的功能,如果有人试图调用它们,将产生LNK2019(未解析的外部)。定义它们,删除它们,或使Bicycle成为一个抽象类。自行车也有孩子,所以给它一个虚拟的析构函数。
Bicycle(int, char*);
virtual ~Bicycle() = default;
virtual void speedup();
virtual void speeddown();
virtual void turnLeft();
virtual void turnRight();
您正在定义属于MotorBike成员的函数,但您从未声明过它们。将它们添加到MotorBike的声明中:
class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
Motorbike(int,char*,int,int);
void speedup();
void speeddown();
};
在摩托车中覆盖自行车功能时使用override
关键字:
class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
Motorbike(int,char*,int,int);
void speedup() override; // like this
void speeddown() override; // and this
};
或者,或者,使用Bike在MotorBike中实现的任何默认功能:
class MotorBike:public Bicycle
{
private:
int currentGear;
int currentFuel;
public:
Motorbike(int,char*,int,int);
using Bicycle::speedup; // like this
using Bicycle::speeddown; // and this
};
修复您的数据类型。 MotorBike将currentGear
和currentFuel
声明为整数,但在MotorBike::speedup
中,您可以向它们添加浮点值。这不起作用,因为这些值的小数部分将被截断。