给一个实例证明virtual的作用
时间: 2024-03-22 08:37:41 浏览: 18
好的,以下是一个简单的示例,说明了virtual的作用:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" << endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle(int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" << endl;
return (width * height);
}
};
class Triangle: public Shape {
public:
Triangle(int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" << endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// 存储矩形的地址
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
// 存储三角形的地址
shape = &tri;
// 调用三角形的求面积函数 area
shape->area();
return 0;
}
```
在上面的示例中,我们定义了一个基类Shape和两个派生类Rectangle和Triangle,它们都重写了基类中的虚函数area()。在main()函数中,我们首先创建了一个Rectangle对象rec和一个Triangle对象tri,然后声明了一个指向Shape类型的指针shape,并将其指向rec和tri。接着,我们调用了shape->area(),这里的area()函数是虚函数,在运行时根据对象的实际类型来调用正确的函数,即Rectangle类的area()和Triangle类的area()函数。
通过运行程序,可以看到输出结果为:
```
Rectangle class area :
Triangle class area :
```
这说明程序在运行时根据对象的实际类型来调用了正确的函数。如果我们没有使用virtual关键字将area()函数声明为虚函数,那么程序将根据指针或引用类型来调用函数,而不是根据对象的实际类型来调用函数,这样就无法实现多态性的特性。