C++问题,急求解答。。。
1.设计一个vehicle基类,包含Run()和Stop()等成员函数,并派生出bicycle类和motocar类,由这两个派生类继续派生出motocycle类,每个派生...
1. 设计一个vehicle基类,包含Run()和Stop()等成员函数,并派生出bicycle类和motocar类,由这两个派生类继续派生出motocycle类,每个派生类中都有自己的与基类中功能不同的Run()和Stop()成员函数。
要求:
(1)在主函数中分别声明vehicle类、bicycle类、motocar类、motocycle类的对象,通过这些对象调用Run()和Stop()成员函数,要求每个对象能够调用对象所属派生类自己的成员函数。
(2)声明vehicle类的指针,让此对象指针依次指向vehicle类、bicycle类、motocar类、motocycle类的对象,并同时用该对象指针调用调用Run()成员函数。 展开
要求:
(1)在主函数中分别声明vehicle类、bicycle类、motocar类、motocycle类的对象,通过这些对象调用Run()和Stop()成员函数,要求每个对象能够调用对象所属派生类自己的成员函数。
(2)声明vehicle类的指针,让此对象指针依次指向vehicle类、bicycle类、motocar类、motocycle类的对象,并同时用该对象指针调用调用Run()成员函数。 展开
2个回答
展开全部
代码如下:
#include <iostream>
using namespace std;
//基类
class vehicle {
public:
virtual void Run() {
cout<<"vehicle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"vehicle::Stop()被调用了"<<endl;
}
};
//一级派生类
class bicycle : public vehicle {
public:
virtual void Run() {
cout<<"bicycle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"bicycle::Stop()被调用了"<<endl;
}
};
//一级派生类
class motocar : public vehicle {
public:
virtual void Run() {
cout<<"motocar::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"motocar::Stop()被调用了"<<endl;
}
};
//二级派生类
class motocycle : public motocar,public bicycle {
public:
virtual void Run() {
cout<<"motocycle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"motocycle::Stop()被调用了"<<endl;
}
};
int main() {
//用vehicle型指针指向4种对象
vehicle* vehiclePtr1 = new vehicle;
vehicle* vehiclePtr2 = new bicycle;
vehicle* vehiclePtr3 = new motocar;
bicycle* bicyclePtr = new motocycle;
vehicle* vehiclePtr4 = bicyclePtr;
//用vehicle型指针调用4种Run()
vehiclePtr1->Run();
vehiclePtr2->Run();
vehiclePtr3->Run();
vehiclePtr4->Run();
return 0;
}
#include <iostream>
using namespace std;
//基类
class vehicle {
public:
virtual void Run() {
cout<<"vehicle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"vehicle::Stop()被调用了"<<endl;
}
};
//一级派生类
class bicycle : public vehicle {
public:
virtual void Run() {
cout<<"bicycle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"bicycle::Stop()被调用了"<<endl;
}
};
//一级派生类
class motocar : public vehicle {
public:
virtual void Run() {
cout<<"motocar::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"motocar::Stop()被调用了"<<endl;
}
};
//二级派生类
class motocycle : public motocar,public bicycle {
public:
virtual void Run() {
cout<<"motocycle::Run()被调用了"<<endl;
}
virtual void Stop() {
cout<<"motocycle::Stop()被调用了"<<endl;
}
};
int main() {
//用vehicle型指针指向4种对象
vehicle* vehiclePtr1 = new vehicle;
vehicle* vehiclePtr2 = new bicycle;
vehicle* vehiclePtr3 = new motocar;
bicycle* bicyclePtr = new motocycle;
vehicle* vehiclePtr4 = bicyclePtr;
//用vehicle型指针调用4种Run()
vehiclePtr1->Run();
vehiclePtr2->Run();
vehiclePtr3->Run();
vehiclePtr4->Run();
return 0;
}
2010-07-15
展开全部
谢谢了。不过我早就已经自己写出来了。。。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询