c++ - 使用指针和普通变量调用基类函数的区别

标签 c++

// pointers to base class
#include <iostream>
using namespace std;

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; }
};

class Triangle: public Polygon {
  public:
    int area()
      { return width*height/2; }
};

int main () {
  Rectangle rect;
  Triangle trgl;
  //Polygon * ppoly1 = &rect;
  //Polygon * ppoly2 = &trgl;
  //ppoly1->set_values (4,5);
  //ppoly2->set_values (4,5);
    Polygon  ppoly1 = rect;
    Polygon  ppoly2 = trgl;
    ppoly1.set_values (4,5);
    ppoly2.set_values (4,5);

  cout << rect.area() << '\n';
  cout << trgl.area() << '\n';
  return 0;
}

我知道注释行(当 Polygon 的指针用于调用函数时,它很好)。为什么我们需要一个指针,为什么我们不能只使用 Polygon 类型的普通变量。我试过编译,它编译得很好,但没有给出正确的结果。为什么会这样?

最佳答案

  • 当您将 Rectangle/Triangle 分配给 Polygon 时,您正在对对象进行切片。参见 What is the slicing problem in C++?

  • 然后您对(切片的)拷贝 调用set_values,因此当您计算原始多边形的面积时,实际上没有设置任何值。

  • 您的基类 Rectangle 也应该定义一个虚析构函数,int area() 应该是 Polygon< 的 const 纯虚方法

关于c++ - 使用指针和普通变量调用基类函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171634/

相关文章:

c++ - 可以使用 std::launder 将对象指针转换为其封闭数组指针吗?

c++ - 为什么没有include语句头文件编译成功?

c++ - Qt 5.7 和 5.11 版本之间的演变有多重要?

c++ - 将 QStandardItemModel 从 C++ 传递到 QtQuick/QML TableView 并显示它

c++ - Boost::signals2 - 传递信号槽作为参数

c++ - 字符串 vector 输入和查询操作

c++ - 如何在解析文本 C++ 时删除注释

c++ - 使用 swig 到 ocaml 的奇怪重命名行为

c++ - 检测进程内存是否被操纵?

c++ - 如何在 C++ Metro 应用程序中制作 HTTP POST/GET?