我无法为矢量编写一个getter

时间:2015-11-08 17:25:04

标签: c++ vector

为什么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

1 个答案:

答案 0 :(得分:7)

因为getSomeVector会返回someVector的副本。所以你要更新一个临时对象,然后立即销毁。尝试将其更改为vector<int>& getSomeVector()