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

标签 c++ class inheritance

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

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/

相关文章:

c++ - C++中通过继承类重命名类成员

c# - 流是什么意思?它的特点是什么?

java - 多重继承序列化保持向后兼容性

c++ - 私有(private)/保护变量 "error: within this context"

C++,通过指针传递泛型数组,继承,错误: no operator which takes a right-hand operand

python - 发现未记录程序的 IPC 接口(interface)?

c++ - std::string 附加太慢?

c++ - Visual Studio 版本之间的库 ABI 兼容性

ruby - 猴子修补 Object 以更自然的方式测试元素是否在数组中是不是一个坏主意?

C++读取txt文件时遇到问题