C++语言程序设计

还是上面的例子,我们把基类的成员函数定义为虚函数,即:

| 例11-19

class vehicle
{
…
virtual void message(void) {cout << "Vehicle message\n";}
};
并将main函数修改为:
void main()
{
vehicle *unicycle;

unicycle = new vehicle;
unicycle->message();
delete unicycle;

unicycle = new car;
unicycle->message();
delete unicycle;

unicycle = new truck;
unicycle->message();
delete unicycle;

unicycle = new boat;
unicycle->message();
delete unicycle;
}

该程序的运行结果为:
Vehicle message
Car message
Vehicle message
Boat message