欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实验7.2 定义一个车(vehicle)基类,使用虚函数实现动态多态性

程序员文章站 2022-04-21 23:30:10
...

题目

定义一个车(vehicle)基类,有Run、Stop等成员函数,由此派生出自行车(bicycle)类、汽车(motorcar)类,从bicycle和motorcar派生出摩托车(motorcycle)类,它们都有Run、Stop等成员函数。观察虚函数的作用。

C++代码如下:

#include<iostream>
using namespace std;

class vehicle
{
public:
	 void Run(){cout<<"Vehicle is running."<<endl;}
	 void Stop(){cout<<"Vehicle is stopping."<<endl;}
};
class bicycle: public vehicle
{
public:
	void Run(){cout<<"Bicycle is running."<<endl;}
	void Stop(){cout<<"Bicycle is stopping."<<endl;}
};
class motorcar: public vehicle
{
public:
	void Run(){cout<<"Motorcar is running."<<endl;}
	void Stop(){cout<<"Motorcar is stopping."<<endl;}
};
class motorcycle:public bicycle,public motorcar
{
public:
	void Run(){cout<<"Motorcycle is running."<<endl;}
	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() ; 
//	p=&mcycle;
//	p->Run() ;
//	p->Stop() ; 
	
	return 0;
}

实验7.2 定义一个车(vehicle)基类,使用虚函数实现动态多态性