【发布时间】:2015-02-24 14:43:56
【问题描述】:
我想将shared_ptr<derived> 添加到具有shared_ptr<base> 值的地图中(如下http://ideone.com/hd68yc)但它失败了(我们到达EXIT_FAILURE):
#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;
}
}
【问题讨论】:
标签: c++ inheritance