2012-07-11 73 views
0

所以我有一个具有以下类型的受保护的指针成员在递归函数中覆盖函数参数?

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

我也有相同类的公共递归成员函数声明如下

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

递归函数的类通过子节点进行检查,如果子节点的名称与作为参数传入的字符串相匹配,则会将父节点的地址分配给storeParentinThis。

这就是我如何从同一类的另一个函数调用函数。

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

然而,在运行时期间,当我输出存储在assigntoThis I的值获得00000000 = NULL。如何在递归函数中更改assigntoThis的值?

+0

对于这里未来的参考是线程后面这个问题的理由http://stackoverflow.com/questions/1898524/difference-between-pointer-to-a-reference-and-reference-to-a指针 – user1084113 2012-07-11 19:01:59

回答

3

变化:

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; 
} 
+0

非常感谢。 – user1084113 2012-07-11 18:16:59

+1

你应该解释_why_它的工作原理。 :) – Chad 2012-07-11 18:20:09

+0

是的,这会帮助 – user1084113 2012-07-11 18:20:36