2010-09-15 154 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