2012-07-11 72 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