车的不同行为(pta)

我记录这道题有两个原因:
一是我竟然在csdn博客中找不到这道题目。虽然有同名的题目,但在main函数中仍有很大区别。
二是这道题目是在学多态时遇到的,我却用的函数重载,虽然结果是正确的,但是我认为有更好的方法,我却想不出来。如果你有更好的方法,请在下方留言。

定义一个车(vehicle)基类,有虚函数Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,它们都有Run、Stop等成员函数。完成这些类使得主函数可以运行并得到正确的输出结果。

函数接口定义:
完成类代码。

裁判测试程序样例:


/* 请在这里填写答案 */
int main(int argc, char const *argv[])
{
    Vehicle veh;
    Bicycle bic;
    Motorcar mot;
    run(veh);
    run(bic);
    run(mot);
    return 0;
}


输入样例:

输出样例:
在这里给出相应的输出。例如:

Vehicle run
Bicycle run
Motorcar run

代码:

#include<iostream>
using namespace std;
class Vehicle
{
public:
     void run(){
        cout<<"Vehicle run"<<endl;
    }
     void stop(){
        cout<<"Vehicle stop"<<endl;
    }
};
class Bicycle:public Vehicle
{
public:
    void run(){
        cout<<"Bicycle run"<<endl;
    }
    void stop(){
        cout<<"Bicycle stop"<<endl;
    }
};
class Motorcar:public Vehicle
{
public:
    void run(){
        cout<<"Motorcar run"<<endl;
    }
    void stop(){
        cout<<"Motorcar stop"<<endl;
    }
};
void run(Vehicle v){
    v.run();
}
void run(Bicycle b){
    b.run();
}
void run(Motorcar m){
    m.run();
}

Logo

欢迎大家加入成都城市开发者社区,“和我在成都的街头走一走”,让我们一起携手,汇聚IT技术潮流,共建社区文明生态!

更多推荐