實驗7.2 定義一個車(vehicle)基類,使用虛函數實現動態多態性

題目

定義一個車(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;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章