Assigning value to function returning reference

后端 未结 7 957
温柔的废话
温柔的废话 2020-12-19 07:53
#include
using namespace std;

int &fun()
{
  static int x = 10;
  return x;
}
int main()
{
   fun() = 30;
   cout << fun();
   return 0;
}         


        
7条回答
  •  没有蜡笔的小新
    2020-12-19 08:06

    In addition to other answers, consider the following code:

    SomeClass& func() { ... }
    
    func().memberFunctionOfSomeClass(value);
    

    This is a perfectly natural thing to do, and I'd be very surprised if you expected the compiler to give you an error on this.

    Now, when you write some_obj = value; what really happens behind the scenes is that you call some_obj.operator =(value);. And operator =() is just another member function of your class, no different than memberFunctionOfSomeClass().

    All in all, it boils down to:

    func() = value;
    // equivalent to
    func().operator =(value);
    // equivalent to
    func().memberFunctionOfSomeClass(value);
    

    Of course this is oversimplified, and this notation doesn't apply to builtin types like int (but the same mechanisms are used).

    Hopefully this will help you understand better what others have already explained in terms of lvalue.

提交回复
热议问题