【问题标题】:Overwriting function parameter in a recursive function?在递归函数中覆盖函数参数?
【发布时间】:2012-07-11 18:12:23
【问题描述】:

所以我有一个具有以下类型的受保护指针成员的类

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 中的值时,我得到 00000000 = NULL。如何在递归函数中更改 assigntoThis 的值?

【问题讨论】:

标签: c++ function recursion parameters assign


【解决方案1】:

改为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 2012-07-20
    • 2016-07-22
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多