欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

虚基类

程序员文章站 2022-06-08 18:09:55
...

【任务

在【任务3的基础上,由自行车(Bicycle)类、汽车(Motorcar)类派生出摩托车(MotorCycle)类。在继承过程中注意把Vehicle设置为虚基类

实验要求

如果不把Vehicle设置为虚基类,会有什么问题?并分析原因。

#include <iostream>
using namespace std;
class Vehical
{
public:
	Vehical(){Weight=0;Maxspeed=0;}
	~Vehical(){}
protected:
	int Maxspeed;
	int Weight;
};
class Bike:virtual  public Vehical
{
public:
	Bike(){Height=1;}
	void Set(int s,int w){Maxspeed=s;Weight=w;}
	~Bike(){}
	void Display(){cout<<"The information of Bike:\n"<<"Maxspeed:"<<Maxspeed<<"m/s.\n"<<"Weight:"<<Weight<<"kg.\n"<<"Height:"<<Height<<"m."<<endl;}
protected:
	int Height;
};
class Motorcar:virtual public Vehical
{
public:
	Motorcar(){SeatNum=2;}
	~Motorcar(){}
	void Set(int s,int w){Maxspeed=s;Weight=w;}
	void Display(){cout<<"The information of Motorcar:\n"<<"Maxspeed:"<<Maxspeed<<"m/s.\n"<<"Weight:"<<Weight<<"kg\n"<<"SeatNum:"<<SeatNum<<"."<<endl;}
protected:
	int SeatNum;
};
class MotorCycle:public Bike,public Motorcar
{
	public:
		MotorCycle(){};
		~MotorCycle(){};
		void Set(int s,int w,int h,int t){Maxspeed=s;Weight=w;Height=h;SeatNum=t;}
		void Display(){cout<<"The information of Motorcar:\n"<<"Maxspeed:"<<Maxspeed<<"m/s.\n"<<"Weight:"<<Weight<<"kg\n"<<"Height:"<<Height<<"m.\n"<<"SeatNum:"<<SeatNum<<"."<<endl;}
};
int main()
{
	Bike b;
	Motorcar c;
	MotorCycle d;
	b.Set(10,50);
	c.Set(100,100);
	d.Set(120,100,1,3);
	b.Display();
	c.Display();
	d.Display();
	return 0;
} 
虚基类

      如果不把Vehicle设置成虚基类的话,会出现[Error] reference to 'Maxspeed' is ambiguous等错误,因为编译器认为继承的Maxspeed是含糊不清的,继承的两个类BikeMotorcar里面都有Maxspeed




相关标签: c++ 虚基类