Getters/Setters with std::vector<>.push_back(…)

冷暖自知 提交于 2019-12-20 02:13:24

问题


For some reason this doesn't work. It compiles file, but no items are added to this vector when using a getter.

E.G.

class class_name {

    public:
        inline std::vector<int> get_numbers() { return m_numbers; }    

    private:
        std::vector<int> m_numbers;
}

....

{
    class_name number_list;
    number_list.get_numbers().push_back(1);
}

If I do it directly (m_numbers.push_back(1)) it works, but if I pull it out with a getter it won't add anything.


回答1:


Return the vector by reference if you plan to modify it:

inline std::vector<int> &get_numbers() { return m_numbers; }  
                        ^

Without the ampersand a copy is returned.



来源:https://stackoverflow.com/questions/12851516/getters-setters-with-stdvector-push-back

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!