gpt4 book ai didi

c++ - 通过引用类的构造函数传递 std::map 不更新 map

转载 作者:行者123 更新时间:2023-11-28 00:19:59 25 4
gpt4 key购买 nike

我试图理解为什么在引用 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。我尝试通过引用将 map 传递给函数 func,这很有效, map 很好地“更新”了。显然,我从构造函数中遗漏了一些东西,由于某些原因创建了一个新 map 并且不再更新我在 main 函数中提供的 map 。

感谢您的帮助!

最佳答案

您可能通过引用传递 map ,但您的数据成员不是引用:

std::map<string, Foo*> f;

所以当你这样做的时候

this->f = f;

您复制了输入参数f。这个简单的代码说明了这个问题:

void foo(int& i)
{
int j = i;
j = 42; // modifies `j`, not i`.
}

关于c++ - 通过引用类的构造函数传递 std::map 不更新 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28014199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com