我创建了三个类:Square,Rectangle和Polygon。 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构造函数,一切正常。但我想有两个构造函数。有什么我可以做的吗?
'类方形:公共Rectangle'哦... – SingerOfTheFall
你不叫矩形直接构造所以默认的构造函数将被调用......然而,没有默认的构造函数,你必须定义它或直接调用你的构造函数。 – Melkon
正方形/矩形实际上在其他地方作为反对继承的示例进行了讨论。人们可能会试图反转继承关系,这也会导致其他问题。也就是说,在边上调用Rectangles ctor:'Square(int side):Rectangle(side,side){...}'哦,Petr在关于Square的ctor的回答中有一点。 –