C++作业声名一个基类vehicle,有私有成员maxspeed和weight,公有成员run()和stop(),以及构造和析构函数。(虚基类)

【问题描述】

声名一个基类vehicle,有私有成员maxspeed和weight,公有成员run()和stop(),以及构造和析构函数。

从vehicle派生bicycle和motorcar, bicycle有私有成员height, motorcar有私有成员seatnum,以及各自的构造函数和析构函数。

从bicycle和motorcar派生出motorcycle,观察虚基类对继承的影响。

定义一个motorcycle的对象,分别调用run()和stop(),观察构造/析构函数的调用情况。

注意:构造函数和析构函数中均为cout语句,说明哪个构造/析构函数被调用。

该题重点和难点在于构造函数的设计,需考虑怎么给基类及最远基类传递参数。

【样例输出】

vehicle constructor called. maxspeed:3; weight4

bicycle constructor called. height:1

motorcar constructor called. seatnum:2

motorcycle constructor called

vehicle run

vehicle stop

motorcycle destructor called

motorcar destructor called. seatnum:2

bicycle destructor called. height:1

vehicle destructor called. maxspeed:3; weight4

【C++代码】

#include  "iostream" 
using  namespace  std; 
class vehicle
{
private:
	int maxspeed,weight;
public:
	vehicle(int _maxspeed,int _weight);
	~vehicle(); 
	void run();
	void stop();
};
vehicle::vehicle(int _maxspeed,int _weight)
{
	maxspeed=_maxspeed;
	weight=_weight;
	cout<<"vehicle constructor called. maxspeed:"<<maxspeed<<";weight"<<weight<<endl;
}
vehicle::~vehicle()
{
	cout<<"vehicle destructor called. maxspeed:"<<maxspeed<<";weight"<<weight<<endl;
}
void vehicle::run()
{
	cout<<"vehicle run"<<endl;
} 
void vehicle::stop()
{
	cout<<"vehicle stop"<<endl;
} 
//
class bicycle :virtual public vehicle
{
public:
	bicycle(int h,int m,int w);
	~bicycle();
private:
	int height;
};
bicycle::bicycle(int h,int m,int w):vehicle(m,w)
{
	height=h;
	cout<<"bicycle constructor called. height:"<<height<<endl;
}
bicycle::~bicycle()
{
	cout<<"bicycle destructor called. height:"<<height<<endl;
}
//
class motorcar :virtual public vehicle
{
public:
	motorcar(int s,int m,int w);
	~motorcar();
private:
	int seatnum;
};
motorcar::motorcar(int s,int m,int w):vehicle(m,w)
{
		seatnum=s;
	cout<<"motorcar constructor called. seatnum:"<<seatnum<<endl;
}

motorcar::~motorcar()
{
	cout<<"motorcar destructor called. seatnum:"<<seatnum<<endl;
};
//
class motorcycle : public bicycle,public motorcar
{
public:
	motorcycle(int h,int s,int m,int w);
	~motorcycle();	
};
motorcycle::motorcycle(int h,int s,int m,int w):bicycle(h,m,w),motorcar(s,m,w),vehicle(m,w)
{
	cout<<"motorcycle constructor called"<<endl;
}
motorcycle::~motorcycle()
{
	cout<<"motorcycle destructor called"<<endl;
};
//
int  main(int  argc,  char  *argv[]) 
{ 
        motorcycle  m(1,  2,  3,  4);//1表示height,2表示setnum,3表示maxspeed,4表示weight 
        m.run(); 
        m.stop(); 
        return  0; 
}

【测试样例】
在这里插入图片描述

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值