c++ - 在递归函数中覆盖函数参数?

标签 c++ function recursion parameters assign

所以我有一个具有以下类型的 protected 指针成员的类

int *assigntoThis; // In the constructor I have initialized this to NULL.

我还有一个具有以下声明的同一类的公共(public)递归成员函数

bool find(int* parent, std::string nameofnode, int* storeParentinThis);

递归函数检查子节点,如果子节点的名称与作为参数传入的字符串匹配,它将父节点的地址分配给 storeParentinThis。

这就是我从同一类的另一个函数调用该函数的方式。

bool find(root, "Thread", assigntoThis);

但是,在运行时,当我输出存储在 assigntoThis 中的值时,我得到 00000000 = NULL。如何在我的递归函数中更改 assigntoThis 的值?

最佳答案

更改为:

bool find(int* parent, std::string nameofnode, int*& storeParentinThis);

解释:

这是原始代码的简化版本:

foo (int* p) { /// p bahaves as a local variable inside foo
  p = 1;  
}    
int* p = 0;
foo(p);
// here p is still equal 0

这实际上类似于下面的代码:

foo (int i) {
  i = 1;  
}    
int i = 0;
foo(i);
// here i is still equal 0

我觉得这样更容易理解。

因此,如果我们想从函数返回一些东西,我们必须创建一个指向它的指针或对它的引用,通过示例向后:

foo (int* i) { // pointer example
  *i = 1;  
}    
int i = 0;
foo(&i);
// here i is equal to 1

foo (int& i) { // using reference example
  i = 1;  
}    
int i = 0;
foo(i);
// here i is equal to 1

现在很容易将它应用到您的案例中:

// pointer example
bool find(int* parent, std::string nameofnode, int** storeParentinThis) {
    *storeParentinThis = parent;
}

// reference example
bool find(int* parent, std::string nameofnode, int*& storeParentinThis) {
     storeParentinThis = parent;
}

关于c++ - 在递归函数中覆盖函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11438804/

相关文章:

c++ - 我有一个应该打印数组的函数,但由于某种原因它不起作用

Javascript - 您可以使用 .shift() 在递归过程中更改数组吗?

javascript - 递归程序打印数字时出现问题

c++ - 如何查看 CMake 使用了哪些 gcc 选项?

c++ - 使用命令行参数进行调试时,Visual Studio C++ 抛出异常 : read access violation.

c - C程序输出错误

javascript - 在 JavaScript 中向函数内的对象添加属性?

java - Minecraft,服务器在生物生成 1.9 时崩溃

使用 do while 和 switch 的 C++ 程序菜单

c++ - Qt:如何在点击按钮时打开一个新的主窗口并删除原来的主窗口?