2010-09-15 11 views
9

जब यह कोड मैं निम्नलिखित 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 
} 

मैं क्यों समझ में नहीं आता? क्या कोई समझा सकता है?

+1

क्या त्रुटि – Mark

+1

है कृपया संकलक से सटीक त्रुटि संदेश पोस्ट। –

+0

आपकी टेम्पलेट घोषणा पैरामीटर श्रेणी पर निर्भर नहीं है। –

उत्तर

9

सी ++ अस्थायी में गैर-निरंतर संदर्भों के लिए बाध्य नहीं किया जा सकता है।

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

यहाँ आप एक गैर निरंतर संदर्भ mainReference जो अमान्य है के लिए एक rvalue अभिव्यक्ति का परिणाम असाइन करने की कोशिश कर रहे हैं।

बनाने का प्रयास करें यह const

+2

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

+0

@Ugo: हाँ, अच्छा लेख। अापका नजरिया क्या है? –

+0

धन्यवाद प्रसुण सौरव। – Donald

संबंधित मुद्दे