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>}’
通常的方法是'return stringAttribute;'。如果出現錯誤,則需要在問題中包含錯誤消息的完整文本。 –
@PeteBecker我試過了,但是我有這個錯誤: 錯誤:類型'std :: string&{aka std :: basic_string&}'的引用無效初始化類型'const string {aka const std :: basic_string }' –
好綽號法國人:D –