C++语言程序设计

为了说明虚函数的作用，我们先看一个程序实例：

| 例11-17

#include <iostream.h>
class vehicle
{
int wheels;
float weight;
public:
void message(void) {cout << "Vehicle message\n";}
};

class car : public vehicle
{
int passenger_load;
public:
void message(void) {cout << "Car message\n";}
};

class truck : public vehicle
{
int passenger_load;
float payload;
public:
int passengers(void) {return passenger_load;}
};

class boat : public vehicle
{
int passenger_load;
public:
int passengers(void) {return passenger_load;}
void message(void) {cout << "Boat message\n";}
};

void main()
{
vehicle *unicycle;
car *sedan;
truck semi;
boat sailboat;

unicycle = new vehicle;
unicycle-> message(); //输出Vehicle message
delete unicycle;

unicycle = new car;
unicycle -> message(); //输出Vehicle message

sedan = (car *) unicycle;
sedan -> message(); //输出Car message
delete sedan;

semi.message(); //输出Vehicle message
sailboat.message(); //输出Boat message
}

该程序的运行结果，我们已经标注在程序之中。从11.1.4节的知识，我们可以也很容易分析出它的运行结果。因为指针的类型决定调用那一个成员函数，所以，一个vehicle*调用vehicle成员函数，即使它指向派生类的对象。同样，一个car *也调用car 的成员函数。我们把这称为早期联编或静态联编，因为指针要调用那一个函数是在编译时就确定的。