gpt4 book ai didi

c++ - 不调用父类(super class)构造函数的多级继承

转载 作者:行者123 更新时间:2023-11-27 22:56:24 26 4
gpt4 key购买 nike

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

问题是,每当我调用 Square 构造函数时,都会调用 Rectangle 构造函数,并且出现错误。我该如何解决这个问题?

#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();
}

如果我注释掉 Rectangle 构造函数,一切正常。但我想要两个构造函数。有什么我可以做的吗?

最佳答案

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

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

关于c++ - 不调用父类(super class)构造函数的多级继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com