Return reference to a vector member variable

后端 未结 4 1891
日久生厌
日久生厌 2021-01-30 07:05

I have a vector as member in a class and I want to return a reference to it through a getVector() function, so as to be able to modify it later. Isn’t it better practice the fun

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 07:40

    The reason is that a const member function should only return const references. This is because in a const function, every data member becomes constant.

    Therefore you have to declare the getVector() this way:

    std::vector &VectorHolder::getVector() const;
    

提交回复
热议问题