2017-09-16 38 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的值,您可能会也可能不想要。

相关问题