指向 c++ 中的类对象的指针示例

Example of a pointer to class object in c++

本文关键字:指针 对象 c++ 指向      更新时间:2023-10-16

在 main 函数的以下代码中,shape 被声明为指向类 Shape 对象的指针,但类 Rectangle 的对象地址即 rec 保存在下一行中。有人可以告诉我我的理解错在哪里。

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0)
      {
         width = a;
         height = b;
      }
      int area()
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }
};
class Rectangle: public Shape{
   public:
      Rectangle( int a=0, int b=0)
      {
        Shape(a, b); 
      }
      int area ()
      { 
         return (width * height); 
      }
 };
class Triangle: public Shape{
   public:
      Triangle( int a=0, int b=0)
      {
        Shape(a, b); 
      }
      int area ()
      { 
         return (width * height / 2); 
      }
};

int main( )
{
   Shape *shape;//pointer to Shape class
   Rectangle rec(10,7);
   Triangle  tri(10,5);

  shape = &rec;//address of Rectangle class object saved 
  shape->area();
  shape = &tri;
  shape->area();
  return 0;
}

Shape需要将area声明为virtual以获得多态行为。

virtual int area()
{
...
}

您的代码有几个错误,因此代码没有意义。

例如考虑构造函数

  Triangle( int a=0, int b=0)
  {
    Shape(a, b); 
  }

首先将调用 Shape 的默认构造函数,因为您没有在 ctor 初始化列表中指定对 Shape 构造函数的调用。因此,默认构造函数会将宽度和高度设置为零。在三角形构造函数的主体中,您只需创建一个永远不会使用的 Shape 类型的临时对象。

它可能看起来很糟糕

  Triangle( int a=0, int b=0) : Shape( a, b ) {}

甚至作为

  explicit Triangle( int a=0, int b=0) : Shape( a, b ) {}

如果你知道显式的意思。

除此之外,类层次结构应基于虚函数,您可以获得多态的效果。所以类形状应该按以下方式定义

class Shape {
   protected:
      int width, height;
   public:
      Shape( int a=0, int b=0) : width( a ), height( b ) {}
      virtual ~Shape() {}
      virtual int area() const = 0;
};
      int Shape::area() const
      {
         cout << "Parent class area :" <<endl;
         return 0;
      }

并根据这些更改对派生类进行日期处理。

Rectangle派生自Shape,见行

class Rectangle: public Shape

这称为继承或"是"关系:RectangleShape。因此,Shape*可以指向矩形。例如,可以在基类指针与继承的类指针中找到更多信息吗?或大多数C++涵盖继承的教程。

然而,正如 Roddy 的回答所指出的,你应该在 Shape 中声明areavirtual ,否则调用 shape->area() 将始终调用Shapearea 方法,而不是 Rectangle 提供的覆盖方法。由于area for Shape 并没有真正的意义,您甚至可以考虑将其声明为纯虚拟

virtual int area() = 0;