我创建了三个类: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构造函数,一切正常。但我想拥有两个构造函数。我有什么可以做的吗?
答案 0 :(得分:2)
构造函数应该是
Square(int side) : Rectangle(side, side) { sides = 1; }
因为Rectangle
没有默认构造函数。
答案 1 :(得分:2)
您不应在派生类构造函数中设置基类的成员。相反,请显式调用基类构造函数:
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;
}
};