2015-05-16 51 views
1

我正在考完我的舊考試去學習決賽,並且注意到了一些我仍然不明白的東西。派生類中的默認構造函數

class Shape 
{ 
    private: 
    int center_x, int center_y; 
    public: 
    Shape (int x, int y) : center_x(x), center_y(y); {} //constructor initializer 
} 
class Rectangle : public Shape 
{ 
    private: 
    int length, width; 
    public: 
    Rectangle(): //this is where i have trouble, I am supposed to fill in missing code here 
    //but shape does not have a default constructor, what am i supposed to fill in here? 
    Rectangle (int x, int y, int l, int w) : Shape(x,y);{length = l; width = w;} 
} 

感謝

+0

你能澄清你的問題嗎?位? –

+0

對不起,我應該給給定的構造函數添加定義,當他們給我Rectangle()時,我不知道在冒號後面填充什麼。 – ricefieldboy

+0

密切相關:http://stackoverflow.com/q/1711990/179910 –

回答

0

你可以假定沒有座標爲您的默認矩形定義。所以它會是:

Rectangle(): Shape(x,y) , length(0), width(0) { } 
4

有兩種方法。要麼你調用默認的構造函數的MEM-初始化列表的基類construcor一些默認值,例如(我用零作爲默認值):

Rectangle() : Shape(0, 0), length(0), width(0) {} 

或者你可以委託一切從工作默認的構造函數帶參數的構造函數。

例如

Rectangle() : Rectangle(0, 0, 0, 0) {} 

要考慮到類定義應分號結束。:)

+0

第二種解決方案僅適用於C++ 11不是嗎? – jpo38

+0

謝謝,先生,我會upvote,但我顯然我沒有足夠的代表 – ricefieldboy

+1

@ jpo38是的,這是。現在是什麼年?:) –

1

你問錯了問題。你應該問:

什麼應該默認構造Rectangle是?

一旦你回答這個問題,下面的人會發生:

  • 將清楚如何初始化Shape基地
  • 你會意識到,Rectangle不應該有一個默認的構造函數
  • 你會意識到需要重新設計的東西
相關問題