这是来自http://www.cplusplus.com/doc/tutorial/polymorphism.html的多态性示例(为便于阅读而编辑):
// abstract base class
#include <iostream>
using namespace std;
class Polygon {
protected:
int width;
int height;
public:
void set_values(int a, int b) { width = a; height = b; }
virtual int area(void) =0;
};
class Rectangle: public Polygon {
public:
int area(void) { return width * height; }
};
class Triangle: public Polygon {
public:
int area(void) { return width * height / 2; }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = ▭
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << endl; // outputs 20
cout << ppoly2->area() << endl; // outputs 10
return 0;
}
我的问题是编译器如何知道 ppoly1 是 Rectangle 而 ppoly2 是 Triangle,以便它可以调用正确的 area() 函数?它可以通过查看“Polygon * ppoly1 = ▭”行并知道 rect 是一个 Rectangle 来发现这一点,但这并不是在所有情况下都有效,不是吗?如果你做了这样的事情怎么办?
cout << ((Polygon *)0x12345678)->area() << endl;
假设您被允许访问该随机内存区域。
我会对此进行测试,但我目前无法在我使用的计算机上进行测试。
(我希望我没有遗漏一些明显的东西......)