我遇到的问题是,一旦我更改了变量,稍后引用时它似乎就没有变化 在代码中。
class foo
{
private:
string name;
public:
foo(string _name)
:name(_name)
{}
void info()
{ cout<<name; }
void newName(string new_name)
{ name = new_name; }
};
class bar
{
private:
string _name;
vector<foo> _content;
public:
foo at(int i)
{ return _content.at(i); }
void push_back(foo newFoo)
{ _content.push_back(newFoo); }
};
int main()
{
foo test("test");
bar kick;
kick.push_back(test);
kick.at(0).newName("nice");
kick.at(0).info();
return 0;
}
我希望程序返回“nice”,但它返回“test”。 我想这与范围有关,但我不知道。 我该如何写一些东西来解决这个问题?
最佳答案
该成员函数
foo at(int i)
{ return _content.at(i); }
返回存储在 vector 中的对象的拷贝。
如果你想得到预期的结果,那么返回引用。
foo & at(int i)
{ return _content.at(i); }
const foo & at(int i) const
{ return _content.at(i); }
关于c++ - 变量内部变量的问题一旦更改就会恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59781270/