Assigning value to function returning reference

后端 未结 7 945
温柔的废话
温柔的废话 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:16

    It works becuse the result of that function is an lvalue. References are lvalues. Basically, in the whole point of returning a non-const reference from a function is to be able to assign to it (or perform other modifications of referenced object).

    0 讨论(0)
提交回复
热议问题