Whats the significance of return by reference?

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

    It can be usefull when implementing accessors

    class Matrix
    {
       public:
          //I skip constructor, destructor etc
    
          int & operator ()(int row, int col)
          {
             return m_arr[row + col * size];
          }
    
       private:
          int size;
          int * m_arr;
    }
    
    Matrix m(10);
    m(1,0) = 10;  //assign a value to row 1, col 0
    

提交回复
热议问题