我創建了三個類: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的回答中有一點。 –