2010-09-15 68 views
9

当编译这个代码,我得到以下error非const引用的无效初始化是什么意思?

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 
} 

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

+1

什么是错误 – Mark 2010-09-15 17:10:28

+1

请张贴从编译器确切的错误消息。 – 2010-09-15 17:10:41

+0

您的模板声明不依赖于参数化的类。 – 2010-09-15 17:11:34

回答

9

在C++临时表不能绑定到非常量引用。

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

在这里,你正在试图分配一个rvalue表达非恒定参考mainReference这是无效的结果。

尝试使const

+2

http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ – log0 2010-09-15 17:15:36

+0

@Ugo:是的,好文章。你想说什么? – 2010-09-15 17:20:34

+0

感谢Prasoon Saurav。 – Donald 2010-09-15 17:24:43

相关问题