首页 > 技术文章 > C++面向对象类的实例题目十

zhezh 2014-01-02 15:10 原文

题目描述:

编写一个程序,其中有一个汽车类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


推荐阅读