C 习题与解析(继承和派生-02)

文章作者 100test 发表时间 2007:03:10 16:58:30
来源 100Test.Com百考试题网


6.6 编写一个程序设计一个汽车类vehicle,包含的数据成员有车轮个数wheels和车重weight。小车类car是它的私有派生类其中包含载人数passenger_load。卡车类truck是vehicle的私有派生类其中包含载人数passenger_load和载重量payload,每个类都有相关数据的输出方法。
解:
vehicle类是基类由它派生出car类和truck类将公共的属性和方法放在vehicle类中。
本题程序如下:
本程序的执行结果如下:
#include
class vehicle // 定义汽车类
{
protected:
int wheels. // 车轮数
float weight. // 重量
public:
vehicle(int wheels,float weight).
int get_wheels().
float get_weight().
float wheel_load().
void show().
}.
class car:public vehicle // 定义小车类
{
int passenger_load. // 载人数
public:
car(int wheels,float weight,int passengers=4).
int get_passengers().
void show().
}.
class truck:public vehicle // 定义卡车类
{
int passenger_load. // 载人数
float payload. // 载重量
public:
truck(int wheels,float weight,int passengers=2,float max_load=24000.00).
int get_passengers().
float efficiency().
void show().
}.
vehicle::vehicle(int wheels,float weight)
{
vehicle::wheels=wheels.
vehicle::weight=weight.
}
int vehicle::get_wheels()
{
return wheels.
}
float vehicle::get_weight()
{
return weight/wheels.
}
void vehicle::show()
{
cout << "车轮:" << wheels << "个" << endl.
cout << "重量:" << weight << "公斤" << endl.
}
car::car(int wheels, float weight,
int passengers) :vehicle (wheels, weight)
{
passenger_load=passengers.
}
int car::get_passengers ()
{
return passenger_load.
}
void car::show()
{
cout <<" 车型:小车" << endl.
vehicle::show().
cout << "载人:" << passenger_load << "人" << endl.
cout << endl.
}
truck:: truck(int wheels, float weight,int passengers, float max_load):vehicle(wheels,weight)
{
passenger_load=passengers.
payload=max_load.
}
int truck::get_passengers()
{
return passenger_load.
}
float truck::efficiency()
{
return payload/(payload weight).
}
void truck::show()
{
cout <<"车型:卡车" << endl.
vehicle:: show ().
cout << "载人:" << passenger_load << "人" << endl.
cout << "效率:" << efficiency() << endl.
cout << endl.
}
void main ()
{
car car1(4,2000,5).
truck tru1(10,8000,3,340000).
cout << "输出结果" << endl.
car1. show ().
tru1. show ().
}

输出结果
车型:小车
车轮:4个
重量:2000公斤
载人:5人

车型:卡车
车轮:10个
重量:8000公斤
载人:3人
效率:0.977012



相关文章


深度探索C 对象模型(1)
二级笔试试题基础知识和C程序设计2
C语言考试辅导2单项选择题及答案
C 习题与解析(继承和派生-03)
C 习题与解析(继承和派生-02)
C语言考试辅导3单项选择题及答案
C语言考试辅导1单项选择题及答案
C 习题与解析(继承和派生-01)
C 习题与解析(模板-03)
澳大利亚华人论坛
考好网
日本华人论坛
华人移民留学论坛
英国华人论坛