我需要一些特定段落的解釋,我read here。C++多態概念
所以在第一個例子:
// pointers to base class
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class CRectangle: public CPolygon {
public:
int area()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area()
{ return (width * height/2); }
};
int main() {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = ▭
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
爲什麼我不能簡單地指ppoly1->area()
& ppoly2->area()
?由於這兩個指針(即使它們屬於類CPolygon
)都指向包含派生類對象的地址。
**因爲語言不工作的方式**編譯器不夠聰明,無法確定在執行時它們將指向定義了'area()'的東西,此外,這不是編譯器的工作。 – Beta
您是否閱讀過本教程的其餘部分,其中解釋了虛擬成員? – andy256
@ andy256我的確看過,但我腦子裏仍然有這個問題。另外,當我可以創建派生類的對象並調用它的區域功能並完成我的工作時,爲什麼我會使用基類的指針指向派生類的成員(通過實現虛函數)? –