Whats the significance of return by reference?

后端 未结 11 1262
既然无缘
既然无缘 2021-02-13 00:15

In C++,

function() = 10;

works if the function returns a variable by reference.

What are the use cases of it?

11条回答
  •  时光取名叫无心
    2021-02-13 01:00

    Getters/setters for instance

    class C
    {
        int some_param_;
    public:
        int& param() { return some_param_; }
        int const& param() const { return some_param_; }
    };
    

    but here you should go with some_param being a public int. Containers provide functions that return by reference, eg. vector::operator[] so that you can write v[k] = x.

提交回复
热议问题