2013-03-30 185 views
-1

什麼是正確的方式來做這樣的事情的構造函數?我只能在矩形中設置高度和寬度嗎?類的繼承和構造函數

class Rectangle { 
public: 
    Rectangle(int height, int width); 
    int height, int width; 
}; 

class Square : Rectangle { 
    Square(int height, int width); 
} 
+1

看看http://stackoverflow.com/questions/120876/c-superclass-constructor-calling-rules。 – Aiias

回答

1

您只需撥打派生類的成員初始化列表中基類的構造函數:

class Square : Rectangle { 
    Square(int height, int width): Rectangle(height, width) 
    { 
     //other stuff for Square 
    } 

}

0

你可能想要做這樣說:

Square(int sidelength) : Rectangle(sidelength, sidelength) { } 

這你可以用一個參數來構造Squares,它會用t來調用Rectangle構造函數帽子參數作爲寬度和高度。