定义描述交通工具的抽象类Vehicle,其中包含纯虚函数introduce用于介绍工具的概况。
由Vehicle类派生出两种交通工具——飞机类Plane和火车类Train,再定义普通函数void info(Vehilce * veh),该函数能根据传递的对象正确调用属于所传对象的introduce函数。主函数中,输入字符串飞机或火车,在堆空间上生成相应的对象,传递该对象给info函数,信息显示结束后释放堆空间。
#include<iostream>
#include<string>
using namespace std;
class Vehicle
{
public:
virtual void introduce() const = 0;
};
class Plane : public Vehicle
{
public:
virtual void introduce() const override
{
cout << "一架飞机" << endl;
}
};
class Train : public Vehicle
{
public:
virtual void introduce() const override
{
cout << "一列火车" << endl;
}
};
void info(Vehicle* veh)
{
veh->introduce();
}
int main()
{
string input;
while (cin >> input)
{
Vehicle* v = nullptr;
if (input == "飞机")
{
v = new Plane();
}
else if (input == "火车")
{
v = new Train();
}
if (v)
{
info(v);
delete v;
}
}
return 0;
}