【发布时间】:2020-07-06 23:36:00
【问题描述】:
我有一个类,其中通过引用获取某个成员涉及逻辑,所以我为它创建了一个私有 getter 函数,它在内部工作正常。
我还想提供对相同引用的公共访问,但使用常量修饰符。 由于 public 函数不应修改类的状态,因此使用 const 关键字声明。 但是内部逻辑,因为它通过设计提供对内部成员的引用,所以不应将其声明为 const。
我如何能够使用相同的逻辑来获取引用,并同时提供 const 和非 const 访问点?
这里有我遗漏的模式吗?
下面我编译了一个小例子来演示:
class my_class{
public:
const int& get_my_field() const{
return get_my_field_ref(); //g++: error: error - passing 'const my_class' as 'this' argument discards qualifiers [-fpermissive]
}
private:
int field;
int& get_my_field_ref(){ //g++: warning: note - in call to 'int& my_class::get_my_field_ref()'
/* ..complex logic to get reference.. */
return field;
}
};
【问题讨论】:
-
为什么
get_my_field_ref()必须是非const? -
因为 'g++: error error - 将 'int&' 类型的引用绑定到 'const int' 如果它是 const 则丢弃限定符
-
我了解您遇到的错误。我特别问为什么函数
get_my_field_ref()必须是非const- 而你没有回答。 -
哦,非常感谢您的耐心等待!该接口专门用于内部修改
field。 -
使
field成为mutable成员。这允许在const成员函数中对其进行更改。
标签: c++ reference const-correctness