What does “int& foo()” mean in C++?

前端 未结 9 1814
不思量自难忘°
不思量自难忘° 2021-01-30 11:59

While reading this explanation on lvalues and rvalues, these lines of code stuck out to me:

int& foo();
foo() = 42; // OK, foo() is an lvalue
9条回答
  •  孤城傲影
    2021-01-30 12:38

    int& foo(); is a function returning a reference to int. Your provided function returns int without reference.

    You may do

    int& foo()
    {
        static int i = 42;
        return i;
    }
    
    int main()
    {
        int& foo();
        foo() = 42;
    }
    

提交回复
热议问题