我只是好奇.这里举例如下:
#include <iostream>
class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
int area() { return 0; };
};
class Rectangle: public Polygon {
public:
Rectangle(int a,int b) : Polygon(a,b) {}
int area() { return width*height; }
};
int main () {
Polygon * ppoly1 = new Rectangle (4,5);
std::cout << ppoly1->area() << std::endl;
delete ppoly1;
}
Run Code Online (Sandbox Code Playgroud)
我可以调用area()该对象的功能Rectangle,而不设置虚拟area()的Polygon?或者,这是不可能的和Rectangle的area()永远没有父母的忽视virtual?
如果函数不是虚函数,则编译器根据指针的类型(而不是对象的实际类型)决定调用哪个函数,因此可以使用强制转换:
std::cout << static_cast<Rectangle*>(ppoly1)->area() << std::endl;
Run Code Online (Sandbox Code Playgroud)
警告:在这种情况下静态演员阵容很好,因为您确定演员表会成功.通常情况并非如此,如果转换不成功,您可能会得到未定义的行为.
另请注意,您在此处显示的代码(我假设这只是一个简化示例)是声明方法虚拟的典型示例.只有当你有充分的理由不这样做时,你才会寻找不同的解决方案(例如,看看@axalis的答案).