Vehicle基类

该代码实例展示了C++中虚函数的应用,通过Vehicle基类和Bicycle、Motorcar、Motorcycle派生类的定义,演示了多态特性。Bicycle和Motorcar作为Vehicle的虚基类,使得Motorcycle可以同时继承两者的特性。在main函数中,使用Vehicle指针数组调用run和stop函数,体现了多态的动态绑定特性。
摘要由CSDN通过智能技术生成

题目

定义一个车 (Vehicle) 基类,有 run、stop 等成员函数,由此派生出自行车 (Bicycle) 类、汽车 (Motorcar) 类,从 Bicycle 和 Motorcar 派生出摩托车(Motorcycle)类,它们都有run、stop 等成员函数。观察虚函数的作用。

相关阅读

相关阅读

完整代码

#include<bits/stdc++.h>
using namespace std;

class Vehicle{
public:
    virtual void run()=0;
    virtual void stop()=0;
};
class Bicycle: virtual public Vehicle{
public:
    void run(){
        cout << "Bicycle run !" << endl;
    }
    void stop(){
        cout << "Bicycle stop !" << endl;
    }
};
class Motorcar: virtual public Vehicle{
public:
    void run(){
        cout << "Motorcar run !" << endl;
    }
    void stop(){
        cout << "Motorcar stop !" << endl;
    }
};
class Motorcycle: public Bicycle, Motorcar{
public:
    void run(){
        cout << "Motorcycle run !" << endl;
    }
    void stop(){
        cout << "Motorcycle stop !" << endl;
    }
};
int main(){
    Bicycle bicycle;
    Motorcar motorcar;
    Motorcycle motorcycle;
    Vehicle *v[3] = {&bicycle, &motorcar, &motorcycle};
    for (int i = 0; i < 3; i++) {
        v[i]->run();
        v[i]->stop();
    }
}
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值