변수를 변경하면 나중에 코드에서 참조 할 때 변경되지 않은 것처럼 보이는 문제가 있습니다.
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); }
벡터에 저장된 객체의 복사본을 반환합니다.
예상 결과를 얻으려면 참조를 반환하십시오.
foo & at(int i)
{ return _content.at(i); }
const foo & at(int i) const
{ return _content.at(i); }
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다