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

Why can't my base class pointer variable access functions from the derived class?

本文关键字:函数 派生 访问 基类 我的 指针 变量 不能 为什么      更新时间:2023-10-16
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 指向什么,这个指针如何无法访问矩形类的函数?

为什么 ppoly1->area() 是一个错误

谢谢!

表达式 ppoly1->area() 是一个错误,因为ppoly1被键入到没有声明area方法的Polygon。 当C++尝试评估此成员时,它基本上从 Polygon 开始,没有看到名为area的成员,因此发出错误

听起来您想为Polygon类型提供没有实现的area方法的概念(强制派生类型提供一个)。 如果是这种情况,那么您应该在Polygon中声明一个未实现的虚拟方法

class Polygon { 
  ...
  virtual ~Polygon() { } 
  virtual int area() = 0;
};

基类对其派生类一无所知。定义基类时,尚无任何派生类。

变量 ppoly1 的类型为 Polygon *。类多边形没有方法区域,因此编译器会发出错误。

如果要对派生类使用公共接口,则应在基类中声明它。例如

class Polygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area() const = 0;
    virtual ~Polygon(){}
};
class Rectangle: public Polygon {
  public:
    int area() const
      { return width*height; }
};
int main () {
  Rectangle rect;
  Polygon * ppoly1 = &rect;
  ppoly1->set_values (4,5);
  cout << rect.area() << 'n';
  return 0;
}

ppoly1是一个多边形指针。指针指向 Rectangle 对象这一事实并不使它能够调用 Rectangle 函数;类型仍Polygon* .若要使其能够调用矩形函数,需要使其成为矩形指针,或在 Polygon 类中实现虚拟方法,

例如

virtual int area() const;

这意味着当 Polygon 对象area()调用它时,它将查找派生最多的 area() 实例。ppoly1,这将是Rectangle->area().您可以保持Rectangle代码与以前相同。

关于虚拟功能的维基百科:http://en.wikipedia.org/wiki/Virtual_function