2017-08-02 177 views
0

我想從基類繼承構造函數,但我得到錯誤:C2876:'Poco :: ThreadPool':並非所有的重載都可以訪問。C++只繼承公共構造函數

namespace myNamespace{ 

    class ThreadPool : public Poco::ThreadPool{ 
     using Poco::ThreadPool::ThreadPool; // inherits constructors 
    }; 

} 

波科::線程池有3個構造器,2把公共那些都與缺省初始化參數,以及1個私人之一。

我怎樣才能繼承公共構造函數?

我沒有使用C++ 11。

+5

您沒有使用C++ 11,你想繼承構造函數,什麼? – StoryTeller

+0

肯定有一種方法可以在C++ 11之前做到這一點?這是一個非常重要的功能。 – Blue7

+4

@ Blue7使用['using declaration'](http://en.cppreference.com/w/cpp/language/using_declaration)來繼承構造函數是C++ 11的一個特性,唯一的辦法是做類似的pre-C++ 11是在派生類中手動添加所有構造函數並調用父類。 – Holt

回答

3

如果您不使用C++ 11或更高版本,則無法使用單個使用聲明繼承所有基礎構造函數。

Pre-C++ 11的老方法是在派生類中爲我們想要公開的每個c'tor創建一個相應的c'tor。因此,例如:

struct foo { 
    int _i; 
    foo(int i = 0) : _i(i) {} 
}; 

struct bar : private foo { 
    bar() : foo() {} // Use the default argument defined in foo 
    bar(int i) : foo(i) {} // Use a user supplied argument 
}; 

如果你仍想有一個默認參數一個c'tor,你也可以這樣做:

struct baz : private foo { 
    baz(int i = 2) : foo(i) {} // We can even change what the default argument is 
};