问答题
请使用VC6或使用[答题]菜单打开考生文件夹proj2下的工程proj2,其中定义了vehicle类,并派生出motorcar类和bicycle类。然后以motorcar和bicycle作为基类,再派生出motocycle类。要求将vehicle作为虚基类,避免二义性问题。请在横线处填写适当的代码并删除横线,以实现上述类定义。此程序的正确输出结果应为:
A vehicle is running!
A vehicle has stopped!
A bicycle is running!
A bicycle has stopped!
A motorcar is running!
A motocycle is running!
注意:只在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。
#include <iostream.h>
class vehicle
{
private:
int MaxSpeed;
int Weight;
public:
vehicle(): MaxSpeed(0), Weight(0){
vehicle(int max_speed, int weight): MaxSpeed (max_speed ), Weight (weight)(}
//********** found**********
______Run()
{
cout << "Avehicle is running!" << endl;
}
//********** found**********
______Stop()
{
cout << "A vehicle has stopped!" << endl;
}
};
class bicycle : virtual public vehicle
{
private:
int Height;
public:
bicycle(): Height(0){}
bicycle(int max_speed, int weight,int height)
:vehicle (max_speed, weight), Height(height){};
void Run () {cout << "A bicycle isrunning!" << endl; }
void Stop() {cout << "Abicycle hasstopped!" << endl; }
};
class motorcar : virtual public vehicle
{
private:
int SeatNum;
public:
motorcar(): SeatNum(0) {}
motorcar (int max_speed, intweight, int seat_num)
//********** found**********
:______{}
void Run() {cout << "A motorcar isrunning!" << endl; }
void Stop () {cout << "A motorcarhas stopped!" << endl; }
};
//********** found**********
class motorcycle: ______
{
public:
motorcycle(){}
motorcycle (int max_speed, int weight, int height, int seet_num):bicycle(max_speed, weight, height), motorcar (max_speed, weight, seet_num){};
~motorcycle () {};
void Run () {cout << "A motorcycle is running!" << endl; }
void Stop() {cout << "A motorcycle has stopped!" << endl; }
};
int main()
{
vehicle * ptr;
vehicle a;
bicycle b;
motorcar c;
motorcycle d;
a.Run(); a. Stop();
b.Run(); b. Stop();
ptr = &c; ptr->Run();
ptr = &d; ptr->Run();
return 0;
}
【正确答案】(1)virtual void
(2)virtual void
(3)vehicle(max_speed,weight),SeatNum(seat_num)
(4)public bicycle,public motorcar
【答案解析】[考点] 本题考查vehicle类及其派生类bicycle、和motorcar类和motorcyrcle类,其中涉及虚函数、虚基类、构造函数和成员函数。
[解析] (1)和(2)主要考查考生对虚函数的掌握,虚函数使用virtual定义。
(3)主要考查考生对构造函数的掌握,使用成员列表初始化。
(4)主要考查考生对派生类的掌握,派生类继承基类时要表明继承方式,公有继承为public,多个继承时要使用“,”隔开。