- 我们先不使用 virtual,构造一个最简单的类shape,和它的子类rectangle。
class shape
{
public:
void CalculateArea(){ cout << "There is no area" << endl; }
};
class rectangle: public shape
{
public:
double CalculateArea() { cout << "Area is width*length." << endl; }
};
int main()
{
rectangle* pt_rec = new rectangle;
cout << pt_rec->CalculateArea() << endl;
shape* pt_rec2 = new rectangle; //注意这里类换成了shape
cout << pt_rec2->CalculateArea() << endl;
}
此时输出结果是
Area is width*length
There is no area
可以发现,第二个输出无法调用rectangle类,因为指针类型设置的是shape。为了解决这个问题,我们在 class shape 里加上virtual。
class shape
{
public:
void virtual CalculateArea(){ cout << "There is no area" << endl; }
};
此时再运行程序,输出是
Area is widthlength
Area is widthlength
- 这个过程在类中非常重要。比如假设shape有很多子类,长方形、圆形、三角形、菱形、正方形,在main.cpp中希望有一个函数能调取每种形状的面积计算方式。
double getArea(shape* shape)
{
return shape->CalculateArea();
}
我们不可能在主函数中给每种形状都写一个getArea函数,所以这个getArea的传入参数类型只能为shape。此时类中必须有virtual,不然传进去的所有形状都只能调用shape类中的函数,无法到达各自的子类中。