class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class Rectangle: public Polygon {
public:
int area()
{ return width*height; }
};
int main () {
Rectangle rect;
Polygon * ppoly1 = ▭
ppoly1->set_values (4,5);
cout << rect.area() << '\n';
return 0;
}
在上面的例子中,ppoly1 指向什么,这个指针为什么不能访问rectangle 类的函数?
为什么 ppoly1->area() 是一个错误
谢谢!
最佳答案
表达式ppoly1->area()
是一个错误,因为 ppoly1
输入为 Polygon
没有 area
方法声明。当 C++ 试图计算这个成员时,它实际上是从 Polygon
开始的。没有看到名为 area
的成员并因此发出错误
听起来你想给 Polygon
输入 area
的概念没有实现的方法(强制派生类型提供一个)。如果是这种情况,那么您应该在 Polygon
中声明一个未实现的虚方法。
class Polygon {
...
virtual ~Polygon() { }
virtual int area() = 0;
};
关于c++ - 为什么我的基类指针变量不能从派生类访问函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951377/