通过引用将 std::map 传递给不更新映射的类的构造函数
Passing std::map by reference to constructor of class not updating map
>我试图理解为什么在引用 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;
};
接下来是做一些基本指令的主要:
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
.我尝试通过将映射引用传递给函数,这效果很好,地图很好地"更新"了。显然,我从构造函数中缺少一些东西,由于某些原因创建了一个新地图,并且不再更新我在 main 函数中给出的地图。
感谢您的帮助!
您可能通过引用传递地图,但数据成员不是引用:
std::map<string, Foo*> f;
所以当你这样做时
this->f = f;
创建输入参数的副本 f
。这个简单的代码说明了这个问题:
void foo(int& i)
{
int j = i;
j = 42; // modifies `j`, not i`.
}
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- (SFML)按下键时,播放器构造函数未使用正确的动画进行更新
- 在构造函数中更新指针向量时出现问题
- 构造函数不更新类成员变量
- 通过引用将 std::map 传递给不更新映射的类的构造函数
- 为什么在更新数组时不能指定构造函数