2013-11-01 159 views
2

我有一個Rectangle類和方形類,都具有相同的參數的構造函數(名稱,寬度,高度)從基類繼承構造函數?

於是我想到了創建一個基類稱爲形狀和定義Shape.h構造和讓Rectangle類和Square類繼承Shape類的構造函數。

我面臨的問題是,我真的不知道如何從Shape類繼承構造函數到Rectangle和Square類。

對不起,如果我問一個簡單的問題,因爲我仍然是新的C++。

Shape.h

#include <iostream> 
#ifndef Assn2_Shape_h 
#define Assn2_Shape_h 


class Shape { 

public: 
Shape() { 
    name = " "; 
    width = 0; 
    height = 0; 
} 

Shape(std::string name, double width, double height); 

private: 
    std::string name; 
    double width,height; 
}; 
#endif 

Rectangle.h

#include <iostream> 
#ifndef Assn2_Rectangle_h 
#define Assn2_Rectangle_h 


class Rectangle : public Shape { 
//how to inherit the constructor from Shape class? 
public: 
Rectangle() { 

} 

private: 

}; 
#endif 

Square.h

#include <iostream> 
#ifndef Assn2_Square_h 
#define Assn2_Square_h 


class Square: public Shape { 
//how to inherit the constructor from Shape class? 
public: 
    Square() { 

    } 

private: 

}; 
#endif 
+0

基礎的默認構造函數將自動調用。 – billz

+0

我明白了。非常感謝 – user2935569

回答

4

是的,你可以inherit constructors from a base class。這是一個全有或全無的操作,你不能挑選:

class Rectangle : public Shape 
{ 
    //how to inherit the constructor from Shape class? 
public: 
    using Shape::Shape; 
}; 

這隱式地定義構造函數,如果他們在派生型,讓您構建Rectangles這樣的:

// default constructor. No change here w.r.t. no inheriting 
Rectangle r; 

// Invokes Shape(string, double, double) 
// Default initializes additional Rectangle data members 
Rectangle r("foo", 3.14, 2.72); 

這是一個C++ 11功能,編譯器支持可能會有所不同。最新版本的GCC和CLANG支持它。

+0

VG +1。我認爲你應該明確這個暗示定義了'Rectangle :: Rectangle()'。這在Stroustrup的論文中並不清楚,只是在代碼評論中。 – EJP

+0

@EJP好點。我補充說,還有一個例子。 – juanchopanza

+0

@juanchopanza非常感謝解釋 – user2935569

2

你似乎在問如何調用而不是'繼承'它們。答案是用:語法:

Rectangle() : Shape() { 
// ... 
} 

,其中在每種情況下的參數列表是任何你需要

+0

啊,我明白了。非常感謝 – user2935569

+0

@juanchopanza謝謝。我沒有及時瞭解C++ 11。 – EJP