Whats the significance of return by reference?

后端 未结 11 1240
既然无缘
既然无缘 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:17

    You can also achieve method chaining (if you so desire) using return by reference.

    class A
    {
    public:
        A& method1()
        {
            //do something
            return *this;   //return ref to the current object
        }
        A& method2(int i);
        A& method3(float f);  //other bodies omitted for brevity
    };
    
    int main()
    {
        A aObj;
        aObj.method1().method2(5).method3(0.75);
    
        //or use it like this, if you prefer
        aObj.method1()
            .method2(5)
            .method3(0.75);
    }
    

提交回复
热议问题