【发布时间】:2020-06-19 12:34:10
【问题描述】:
我试图了解创建本地副本时类的成员函数的行为方式 私有变量。 (通过引用访问时不是)
所以我有这段代码,我的理解是这样的:
在成员函数 get_name0() 中,向量“name”是私有数据成员“name”的本地副本。
在 get_name0() 函数中添加元素“f0”应该使对象 np0 具有 {ab, f0} 并且确实如此。这里没问题。
在主函数中添加元素“m0”应该使(?)对象 np0 具有 {ab, f0, m0} 但它具有 {ab, f0, f0}。我不明白为什么会发生这种情况,可能我在某个地方错了?
提前感谢任何为我澄清这一点的人!
class Name_pairs
{
public:
vector<string> get_name0() // this is a member function that returns a copy; name is a local copy
{
name.push_back("f0"); // the copy can be changed by the member function
return name;
}
private:
vector<string> name = {"ab"};
};
int main()
{
Name_pairs np0;
np0.get_name0().push_back("m0"); // this should change the local copy not the "name" object but it doesn't
cout << "\nnp0 object: ";
for (string s : np0.get_name0()) // this should print the local copy from the inside of get_name0() function
cout << s << " ";
}
【问题讨论】:
标签: c++ member-functions