#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);
}
/* 程序执行结果
公共汽车过马路
小汽车过马路
公共汽车过马路
行人过马路
小汽车等红灯
公共汽车等红灯
*/
polymorphism、过马路
最新推荐文章于 2024-07-26 17:55:50 发布