所以我有一个具有以下类型的 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/