polymorphism、过马路

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

//交通工具
class V
{
private:
public:
	//这里曾经把两个函数写成了声明
	virtual void run()
	{

	}
	virtual void stop()
	{

	}
};

class Car : public V
{
private:
public:
	virtual void run()
	{
		cout << "小汽车过马路" << endl;
	}
	virtual void stop()
	{
		cout << "小汽车等红灯" << endl;
	}
	
};

class Bus : public V
{
private:
public:
	virtual void run()
	{
		cout << "公共汽车过马路" << endl;
	}
	virtual void stop()
	{
		cout << "公共汽车等红灯" << endl;
	}
};

class NO11 : public V
{
private:
public:
	virtual void run()
	{
		cout << "行人过马路" << endl;
	}
	virtual void stop()
	{
		cout << "行人等红灯" << endl;
	}
};

//传进去的是对象的指针
void run(V* v)
{
	v->run();
}


//传进去的是引用对象
void stop(V& v)
{
	v.stop();
}

int main()
{
	//指针数组?  分配空间空间后有没有初始化?
	V* vs[5] = {
		new Bus(),new NO11(),new Car(),new Bus(),new Car()
	};
	vs[0]->run();
	//这用法,,,没掌握
	run(new Car());
	run(new Bus());
	run(new NO11());
	Car c;
	Bus b;
	//传递的是引用
	stop(c);
	stop(b);

}

/*  程序执行结果
公共汽车过马路
小汽车过马路
公共汽车过马路
行人过马路
小汽车等红灯
公共汽车等红灯
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值