2017-09-16 89 views
1

我有一個帶有字符串屬性的類,我的getters必須返回字符串&這些屬性的值。在getter中返回字符串引用的正確方法

我設法做到這一點沒有得到錯誤的唯一方法是這樣的:

inline string& Class::getStringAttribute() const{ 
    static string dup = stringAttribute; 
    return dup; 
} 

什麼是寫一個getter返回在C++的私人字符串屬性的字符串中,正確的方法是什麼?

做這樣的:

inline string& Class::getStringAttribute() const{ 
    return stringAttribute; 
} 

獲取我這個錯誤:

error: invalid initialization of reference of type ‘std::string& {aka std::basic_string<char>&}’ from expression of type ‘const string {aka const std::basic_string<char>}’ 
+0

通常的方法是'return stringAttribute;'。如果出現錯誤,則需要在問題中包含錯誤消息的完整文本。 –

+0

@PeteBecker我試過了,但是我有這個錯誤: 錯誤:類型'std :: string&{aka std :: basic_string &}'的引用無效初始化類型'const string {aka const std :: basic_string }' –

+0

好綽號法國人:D –

回答

2

的這裏的問題是,你標記你的方法const。因此,對象內部沒有任何狀態可以改變。如果將別名返回給成員變量(在本例中爲stringAttribute),則允許更改對象內的狀態(對象外部的代碼可能會更改該字符串)。

有兩種可能的解決方案:或者簡單地返回一個string,其中實際上會返回一個stringAttribute的副本(因此對象的狀態保持不變),或者返回一個常量字符串,其中調用方法的任何人不能更改stringAttribute的值。

此外,您可以從getStringAttribute()中刪除const,但是然後任何人都可以更改stringAttribute的值,您可能會也可能不想要。

相關問題