为什么item.someVector.push_back(1);
似乎有效,而不是item.getSomeVector().push_back(1);
?
这是我的测试用例:
#include <iostream>
#include <vector>
using namespace std;
class Item {
public:
vector<int> someVector = vector<int>();
vector<int> getSomeVector()
{
return someVector;
}
};
int main()
{
Item item = Item();
item.getSomeVector().push_back(1);
cout << item.getSomeVector().size() << endl;
cout << item.someVector.size() << endl;
item.someVector.push_back(1);
cout << item.getSomeVector().size() << endl;
cout << item.someVector.size() << endl;
}
// output:
// 0
// 0
// 1
// 1
答案 0 :(得分:7)
因为getSomeVector
会返回someVector
的副本。所以你要更新一个临时对象,然后立即销毁。尝试将其更改为vector<int>& getSomeVector()