[英]How to modify the return value of a member function with constant return type within another member function?
标题似乎矛盾,也许是。 但这是我要在C ++ 11中解决的问题。我正在创建一个二进制搜索树,搜索功能如下所示:
const node* search(char);
我已经使返回类型为常量,因为我不希望外部函数随意更改树(我正在返回node *以允许遍历),但是我也在remove()
函数中使用此函数来查找要被删除。 我希望返回的值可以通过remove()
成员函数进行修改。
显而易见的解决方案似乎是:创建具有非常量返回类型的私有搜索功能,但这似乎不必要地延长了代码。
还有另一种方法可以做到这一点,或者实现类似的功能吗?
您可以轻松地执行此操作以避免代码重复:
class foo {
public:
const node* search(char c) const { return internal_search(c); }
private:
node* internal_search(char c) const {
// actual implementation
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.