2014-12-07 70 views
1

我想知道爲什麼在c + +不能使用父類的構造函數爲特定的簽名,萬一派生類錯過了?爲什麼C++不使用父類構造函數?

例如在下面的示例中,我無法使用std::string初始化dd對象。

#include <iostream> 


class Base 
{ 
    int num; 
    std::string s; 
public: 
    Base(int _num){ num = _num;} 
    Base(std::string _s){ s = _s;} 
}; 

class Derived : public Base { 
public: 
    Derived(int _num):Base(_num){} 
}; 

int main() 
{ 
    Base b(50); 
    Derived d(50); 
    Base bb("hell"); 
    Derived dd("hell"); // <<== Error 
    return 0; 
} 

隨着繼承我希望能擴展一個類,而不是失去以前的功能,但在這裏我感覺失去一些。

在一個更實際的例子,我創建了我的版本的std::string但它不會在某些情況下,像一個std::string

#include <string> 
#include <iostream> 


class MyString: public std::string { 
public: 
    void NewFeature(){/* new feature implementation*/} 
}; 

int main() 
{ 
    MyString s("initialization"); // <<== Error: I expect to initialize with "..." 
    cout<<s;      // <<== Error: I expect to print it like this. 
    return 0; 
} 

有人可以給出一些解釋?

回答

8

如果你想繼承構造也一樣,你需要告訴編譯器代碼:

class Derived : public Base { 
    public: 
    using Base::Base; // <- Makes Base's constructors visible in Derived 
}; 

至於「我爲什麼要做這個?」:便宜的答案是:因爲標準是這樣說的。

這是爲什麼它是猜測(如果你不問委員會成員自己)。他們很可能希望避免「令人驚訝」或「不直觀」的代碼行爲。

+0

雖然'使用std :: string :: std :: string'不起作用,我需要'爲什麼'這個問題。爲什麼「繼承」在這裏聞起來。 – Emadpres 2014-12-07 14:36:44

+1

@Emadpres請參閱[這裏](http://coliru.stacked-crooked.com/a/bc7ea27f32f4594c)瞭解'std :: string'的工作語法。 (幾乎是我在答案中寫的:) :) – 2014-12-07 14:45:29

+0

我真的很驚訝。他們在這個標準中寫了一個特殊的例子,使得像'使用std :: string :: string'這樣的東西(回想一下'std :: string'實際上是'std :: basic_string'的一個特定類型的typedef ... ) – 2014-12-07 14:51:26

0

我沒有足夠的代表標記重複,但Inheriting constructors足夠回答這個問題。

基本上,pre-C++ 11在的標準中不是允許構造函數繼承。 C++ 11改變了這一點,你現在可以繼承構造函數。

相關問題