派生类中的默认构造函数

Default constructor in derived classes

本文关键字:默认 构造函数 派生      更新时间:2023-10-16

我要去旧考试以学习决赛,并注意到一些我仍然不明白的东西。

class Shape
{
  private:
  int center_x, int center_y;
  public:
  Shape (int x, int y) : center_x(x), center_y(y); {} //constructor initializer
}
class Rectangle : public Shape
{
  private:
  int length, width;
  public:
  Rectangle(): //this is where i have trouble, I am supposed to fill in missing code here
  //but shape does not have a default constructor, what am i supposed to fill in here?
  Rectangle (int x, int y, int l, int w) : Shape(x,y);{length = l; width = w;}
}

谢谢

有两种方法。您要么在默认构造函数的mem-Initializer列表中调用带有某些默认值的基本类别构造器,例如(我将零用作默认值):

Rectangle() : Shape( 0, 0 ), length( 0 ), width( 0 ) {}

,或者您可以将所有工作从默认构造函数委托给使用参数的构造函数。

例如

Rectangle() : Rectangle( 0, 0, 0, 0 ) {}

考虑了类定义应以semicolon结尾。:)

您在问错误的问题。你应该问

默认构造的 Rectangle应该是什么?

回答此问题后,以下一个将发生:

  • 将很清楚如何初始化Shape基础
  • 您将意识到Rectangle不应具有默认的构造函数
  • 您会意识到需要重新设计某些东西

您可以假设未针对默认矩形定义坐标。所以是:

Rectangle(): Shape(x,y) , length(0), width(0) { }