【发布时间】:2017-09-16 18:12:11
【问题描述】:
我有一个带有字符串属性的类,我的 getter 必须为这些属性返回字符串和值。
我设法做到这一点而不会出错的唯一方法是这样的:
inline string& Class::getStringAttribute() const{
static string dup = stringAttribute;
return dup;
}
在 C++ 中编写返回私有字符串属性的字符串引用的 getter 的正确方法是什么?
这样做:
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
-
如果你想返回一个可修改的引用,你必须有一个非
const访问器;从const访问器中,您只能返回对成员的const引用。你可以在这两种情况下返回一个 copy (返回一个普通的string对象),尽管如果调用者想要一个副本,如果你返回一个const引用,他总是可以自己制作一个。无论您做什么,都不要做您发布的内容 - 您正在返回一个对立即解除分配的字符串的引用 - 本质上是一个悬空引用。 -
正如@MatteoItalia 指出的(我忽略了),这里的访问器函数标记为
const,但它返回对非常量的引用;这两个不在一起。通常的做法是使用两个访问器:一个标记为const,返回const std::string&,一个未标记const,返回std::string&。
标签: c++ syntax getter-setter