本文主要是介绍实验7.2 定义一个车(vehicle)基类,使用虚函数实现动态多态性,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
定义一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。
C++代码如下:
#include<iostream>
using namespace std;class vehicle
{
public:virtual void Run(){cout<<"Vehicle is running."<<endl;}virtual void Stop(){cout<<"Vehicle is stopping."<<endl;}
};
class bicycle: public vehicle
{
public:virtual void Run(){cout<<"Bicycle is running."<<endl;}virtual void Stop(){cout<<"Bicycle is stopping."<<endl;}
};
class motorcar: public vehicle
{
public:virtual void Run(){cout<<"Motorcar is running."<<endl;}virtual void Stop(){cout<<"Motorcar is stopping."<<endl;}
};
class motorcycle:public bicycle,public motorcar
{
public:virtual void Run(){cout<<"Motorcycle is running."<<endl;}virtual void Stop(){cout<<"Motorcycle is stopping."<<endl;}
};
int main()
{vehicle v;bicycle b;motorcar mcar;motorcycle mcycle;v.Run();v.Stop();b.Run();b.Stop();mcar.Run();mcar.Stop();mcycle.Run();mcycle.Stop(); cout<<"指针调用"<<endl;vehicle* p;p=&v;p->Run() ;p->Stop() ; p=&b;p->Run() ;p->Stop() ; p=&mcar;p->Run() ;p->Stop() ; return 0;
}
这篇关于实验7.2 定义一个车(vehicle)基类,使用虚函数实现动态多态性的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!