我想一個shared_ptr<derived>
添加到地圖shared_ptr<base>
值(如下http://ideone.com/hd68yc),但它失敗(我們到達EXIT_FAILURE
):爲什麼我無法在此代碼中將shared_ptr <Derived>添加到地圖<key_type,shared_ptr <Base>>?
#include <iostream>
#include <map>
#include <memory>
using namespace std;
class base{
public:
base(const int& s = 1):setting{s}{};
int setting;
};
class derived : public base{
public:
derived(const int& s):setting{s}{};
int setting;
};
int main() {
map<string,shared_ptr<base>> m_s;
m_s.insert(make_pair("Name",make_shared<derived>(4)));
// None of these worked either...
//m_s.emplace("Name",make_shared<derived>(4));
//m_s["Name"] = make_shared<derived>(4);
if(4 == m_s.at("Name")->setting){
return EXIT_SUCCESS;
}else{
cout << "setting is " << m_s.at("Name")->setting << " when 4 expected";
return EXIT_FAILURE;
}
}
這可能不是最有趣的問題和答案,但我花了很多時間做一個MVCE,我想我可能會從中得到一些東西! – 2015-02-24 14:44:16
您可能應該將正確的值傳遞給基礎構造函數,而不是使用默認值:'correct_derived(const int&s):base(s){} – dewaffled 2015-02-24 14:49:30
是的,這很合理,謝謝。在實際的代碼中'derived'是谷歌模擬的另一個派生於'base'的類,所以我想我最初試圖保持測試代碼和被測單元是分開的。 – 2015-02-24 14:57:19