C++用虚基类来避免成员变量或成员方法调用的二义性问题

当使用C++编程时,如果不将基类Vehicle声明为虚基类,在多重继承中调用其成员可能会导致二义性。不使用虚基类会导致编译器无法确定成员是来自Bicycle还是Motorcar,从而引发错误。
摘要由CSDN通过智能技术生成

注意:
若在继承时不将Vehicle类声明为虚基类,则在对象mc调用Vehicle类中的成员变量或成员方法时就会产生二义性。因为编译器不知道该成员变量或成员方法是来自Bicycle类还是来自Motorcar类。

/*-----------------------------------------------------
功能:用虚基类来避免成员函数或成员方法调用的二义性问题
运行结果:
60
12
2
100
Black
Vehicle is running...
Vehicle is stopping...
------------------------------------------------------
Author: Zhang Kaizhou
Date: 2019-4-9 16:40:13
-----------------------------------------------------*/
#include <iostream>
#include <string>

using namespace std;

class Vehicle{ // 定义一个交通工具类
public:
    int maxSpeed;
    int weight;
    void setMaxSpeed(int s){ maxSpeed = s; }
    void setWeight(int w){ weight = w; }
    int getMaxSpeed()const{ return maxSpeed; }
    int getWeight()const{ return weight; }
    void run(){ cout << "Vehicle is running..." << endl; }
    void stop(){ cout << "Vehicle is stopping..." << endl; }
};

class Bicycle : virtual
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值