开发者

What does `invalid initialization of non-const reference` mean?

开发者 https://www.devze.com 2023-01-16 02:32 出处:网络
When compiling this code I get the following error: In function \'int main()\': Line 11: error: invalid initialization of non-const reference of type \'Main&\' from a temporary of type \'Main\'

When compiling this code I get the following error:

In function 'int main()': Line 11: error: invalid initialization of non-const reference of type 'Main&' from a temporary of type 'Main'

Here's my code:

template <class T>
struct Main
{
    static Main tempFunction(){
       return Main();
    }
};

int main()
{
   Main<int> &mainReference = Main<开发者_运维知识库;int>::tempFunction(); // <- line 11
}

I don't understand why? Can anyone explain?


In C++ temporaries cannot be bound to non-constant references.

Main<int> &mainReference = Main<int>::tempFunction();

Here you are trying to assign the result of an rvalue expression to a non-constant reference mainReference which is invalid.

Try making it const

0

精彩评论

暂无评论...
验证码 换一张
取 消