我正在尝试插入对我的对象的引用,但出现了大量错误。自定义对象需要修改什么才能插入成功?
代码如下:
#include <map>
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A()
{
cout << "default constructor" << endl;
}
A(A & a)
{
cout << "copy constructor" << endl;
}
A & operator=(A & a)
{
cout << "assignment operator" << endl;
return *this;
}
~A()
{
cout << "destructor" << endl;
}
};
int main()
{
map<string, A&> m1;
A a;
m1["a"] = a;
return 0;
}
更新:
可以创建带有引用的 map ,例如
map<string, A&>
错误是在使用 [] 运算符时。通过进行以下更改,代码可以正常工作
typedef map<string, A&> mymap; int main() { mymap m1; A a; cout << &a << endl; m1.insert(make_pair<string, A&>("a", a)); mymap::iterator it = m1.find("a"); A &b = (*it).second; cout << &b << endl; // same memory address as a return 0; }
最佳答案
您不能在map
中存储引用。请改用指针。
替换:
map<string, A&> m1;
与:
map<string, A*> m1;
或者更好(感谢 WhozCraig!):
map<string, shared_ptr<A> > m1;
关于c++ - 如何在 std::map 中插入自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532157/