我想插入一个对我的对象的引用,但我得到大量的错误。我需要在自定义对象中修改哪些内容才能成功插入?如何在std :: map中插入自定义对象
的代码如下所示:
#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;
}
UPDATE:
它可以创建参照地图如
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; }
[cppreference.com](http://en.cppreference.com/w/cpp/container/map)是非常有用的网站。 – 2013-03-20 18:49:01
请注意,你的拷贝构造函数'A(A&a)'不是你想要的 - 你想要'A(一个const&)',而'operator ='是一样的。这与你的问题无关,这在下面解决。 – Yakk 2013-03-20 18:49:49