多级继承而不调用超类构造函数

multilevel inheritance without calling superclass constructor

本文关键字:超类 构造函数 调用 继承 多级      更新时间:2023-10-16

我已经创建了三个类:正方形,矩形和多边形。Square继承自Rectangle, Rectangle继承自Polygon

问题是,每当我调用矩形构造函数,矩形构造函数被调用,我得到一个错误。我怎么解决这个问题?

#include <iostream>
using namespace std;
// Multilevel Inheritance
class Polygon
{
protected:
    int sides;
};
class Rectangle: public Polygon
{
protected:
    int length, breadth;
public:
    Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
        sides = 2;
    }
    void getDimensions()
    {
        cout << "Length = " << length << endl;
        cout << "Breadth = " << breadth << endl;
    }
};
class Square: public Rectangle
{
public:
    Square(int side)
    {
        length = side;
        breadth = length;
        sides = 1;
    }
};
int main(void)
{
    Square s(10);
    s.getDimensions();
}

如果我注释掉矩形构造函数,一切都可以正常工作。但我想同时拥有两个构造函数。有什么我能做的吗?

不应该在派生类构造函数中设置基类的成员。相反,应该显式地调用基类构造函数:

class Polygon
{
protected:
    int sides;
public:
    Polygon(int _sides): sides(_sides) {} // constructor initializer list!
};
class Rectangle: public Polygon
{
protected:
    int length, breadth;
public:
    Rectangle(int l, int b) :
         Polygon(2), // base class constructor
         length(l),
         breadth(b)
    {}
};
class Square: public Rectangle
{
public:
    Square(int side) : Rectangle(side, side)
    {
        // maybe you need to do this, but this is a sign of a bad design:
        sides = 1;
    }
};

构造函数应为

Square(int side) : Rectangle(side, side) { sides = 1; }

作为Rectangle没有默认构造函数