简体   繁体   English

如何在另一个成员函数中用常量返回类型修改成员函数的返回值?

[英]How to modify the return value of a member function with constant return type within another member function?

The title seems contradictory, and perhaps it is. 标题似乎矛盾,也许是。 But this is the problem I am trying to tackle in C++ 11. I am creating a binary search tree, and the search functions looks something like this: 但这是我要在C ++ 11中解决的问题。我正在创建一个二进制搜索树,搜索功能如下所示:

const node* search(char);

I have made the return type constant as I do not want the tree to be arbitrarily changed by outside functions(I am returning node* to allow traversals), but I am also using this function in the remove() function to find the node to be deleted. 我已经使返回类型为常量,因为我不希望外部函数随意更改树(我正在返回node *以允许遍历),但是我也在remove()函数中使用此函数来查找要被删除。 I want the returned value to be modifiable by the remove() member function. 我希望返回的值可以通过remove()成员函数进行修改。

The obvious solution seems to be: create a private search function with a non constant return type, but that seems to unnescessarily lengthen the code. 显而易见的解决方案似乎是:创建具有非常量返回类型的私有搜索功能,但这似乎不必要地延长了代码。

Is there another way to do this, or achieve a similar functionality? 还有另一种方法可以做到这一点,或者实现类似的功能吗?

You can easily do this to avoid the code duplication: 您可以轻松地执行此操作以避免代码重复:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM