“非const引用的无效初始化”是什么意思? [英] What does `invalid initialization of non-const reference` mean?
本文介绍了“非const引用的无效初始化”是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在编译此代码时,我收到以下错误:
When compiling this code I get the following error:
在函数'int main()':
第11行:错误:初始化类型'Main&'的非const引用从'Main' / p>
In function 'int main()': Line 11: error: invalid initialization of non-const reference of type 'Main&' from a temporary of type 'Main'
这是我的代码:
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?
推荐答案
在C ++临时表中不能绑定到非常量引用。
In C++ temporaries cannot be bound to non-constant references.
Main< int> & mainReference = Main< int> :: tempFunction();
这里你试图将右值表达式的结果赋给非常量引用 mainReference
无效。
Here you are trying to assign the result of an rvalue expression to a non-constant reference mainReference
which is invalid.
尝试使其 const
这篇关于“非const引用的无效初始化”是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文