gpt4 book ai didi

c++ - `invalid initialization of non-const reference` 是什么意思?

转载 作者:可可西里 更新时间:2023-11-01 16:37:55 28 4
gpt4 key购买 nike

编译此代码时,我得到以下 error :

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
}

我不明白为什么?谁能解释一下?

最佳答案

在 C++ 中,临时对象不能绑定(bind)到非常量引用。

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

在这里,您试图将右值表达式的结果分配给非常量引用 mainReference这是无效的。

尝试制作它 const

关于c++ - `invalid initialization of non-const reference` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3720005/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com