Assigning value to function returning reference

后端 未结 7 942
温柔的废话
温柔的废话 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条回答
  •  -上瘾入骨i
    2020-12-19 08:06

    L-value is a locator-value. It means it has address. A reference clearly has an address. The lvalue required you can get if you return from fun() by value:

    #include
    using namespace std;
    
    int fun()
    {
      static int x = 10;
      return x;
    }
    int main()
    {
       fun() = 30;
       cout << fun();
       return 0;
    }
    

提交回复
热议问题