C++面向对象类的实例题目十

题目描述:

编写一个程序,其中有一个汽车类vehicle,它具有一个需要传递参数的构造函数,类中的数据成员:车轮个数wheels和车重weight放在保护段中;小车类car是它的私有派生类,其中包含载人数passager_load;卡车类truck是vehicle的私有派生类,其中包含载人数passager_load和载重量payload。每个类都用相关数据的输出方法。

程序代码:

#include<iostream>
using namespace std;
class Vehicle
{
	public:
		Vehicle(int wl,double wh):wheels(wl),weight(wh){};
		void show()
		{
			cout<<"wheels:"<<wheels<<",weight:"<<weight<<endl;
		}
	protected:
		int wheels;
		double weight;
};
class Car:private Vehicle
{
	public:
		Car(int wl,double wh,int pl):Vehicle(wl,wh),passager_load(pl){};
		void show()
		{
			Vehicle::show();
			cout<<"passager_load:"<<passager_load<<endl;
		}
	private:
		int passager_load;
};
class Truck:private Vehicle
{
	public:
		Truck(int wl,double wh,int pl,double psl):Vehicle(wl,wh),passager_load(pl),payload(psl){};
		void show()
		{
			Vehicle::show();
			cout<<"passager_load:"<<passager_load<<endl;
			cout<<"payload:"<<payload<<endl;
		}
	private:
		int passager_load;
		double payload;
};
int main()
{
	Vehicle v1(4,200);
	v1.show();
	cout<<"===================="<<endl;
	Car c1(4,290,10);
	c1.show();
	cout<<"===================="<<endl;
	Truck t1(4,500,50,200);
	t1.show();
	return 0;
}


结果输出:

wheels:4,weight:200
====================
wheels:4,weight:290
passager_load:10
====================
wheels:4,weight:500
passager_load:50
payload:200


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值