【发布时间】:2015-01-18 20:00:58
【问题描述】:
我试图理解为什么在引用 std::map 的类的情况下,它不会更新在类范围之外引用的映射。
这是我的测试程序:
#include <iostream>
#include <map>
class Foo
{
public:
Foo(int x)
{
this->x = x;
}
void display()
{
cout << x << endl;
}
protected:
int x;
};
class FooTest
{
public:
FooTest(std::map<string, Foo*> & f)
{
this->f = f;
}
void func()
{
f["try"] = new Foo(3);
}
protected:
std::map<string, Foo*> f;
};
接下来是执行一些基本指令的 main :
int main()
{
std::map<string, Foo*> f;
f["ok"] = new Foo(1);
FooTest test(f);
test.func();
for(std::map<string, Foo*>::iterator it = f.begin(); it != f.end(); ++it) {
it->second->display();
}
return 0;
}
这显示1,而我想要1,然后是3。
我尝试通过引用将地图传递给函数 func,效果很好,地图很好地“更新”了。显然,我在构造函数中遗漏了一些东西,由于某些原因创建了一个新地图并且不再更新我在主函数中提供的地图。
感谢您的帮助!
【问题讨论】:
-
std::map<string, Foo*> f;应该是std::map<string, Foo*> & f;
标签: c++ class reference stdmap