C++ 类继承和构造函数

C++ 类继承和构造函数,c++,C++,对于这样的事情,构造函数的正确方法是什么?我是否只在矩形中设置高度和宽度 class Rectangle { public: Rectangle(int height, int width); int height, int width; }; class Square : Rectangle { Square(int height, int width); } 您只需在派生类的成员初始化列表中调用基类构造函数: class Square : Rectangle {

对于这样的事情,构造函数的正确方法是什么?我是否只在矩形中设置高度和宽度

class Rectangle {
public:
   Rectangle(int height, int width);
   int height, int width;
};

class Square : Rectangle {
   Square(int height, int width);
}

您只需在派生类的成员初始化列表中调用基类构造函数:

class Square : Rectangle {
   Square(int height, int width): Rectangle(height, width)
   {
        //other stuff for Square
   }

}

您可能希望这样做:

Square(int sidelength) : Rectangle(sidelength, sidelength) { }
通过这种方式,您可以使用单个参数构造正方形,它将使用该参数作为宽度和高度来调用矩形构造函数。

请查看。