c++ - 为什么我的基类指针变量不能从派生类访问函数?

标签 c++ inheritance

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/

相关文章:

android - 如何在 Project Tango 中使用实验性网格化 API

c++ - for 循环中的 const 值

java - 类层次结构爆炸

scala - 为什么使用非空构造函数扩展抽象类的 Trait 会编译?

java - super(Application.class); 是什么意思?在Java中?

c++ - 虚拟或类型转换

c++ - 如何在 QToolButton QT C++ 中的文本旁边放置箭头图标

python - Python 中用于存储键值对的类与字典

c++ - 没有默认构造函数的对象数组初始化

c++ - 纯虚函数实现