2013-03-05 28 views
0

我在main中創建根。然後在另一個的.cpp我做這樣的事情在節點樹中使用'this'的C++

TreeNode * current = this; 

然後,如果我做

current = current->right; 

這樣我就可以去把樹砍倒。它會改變'這'是指什麼?

+0

很確定我明白了。我做了一個changeThis()自己嘗試,並沒有改變'this'中的任何內容。 – 2013-03-05 10:11:20

回答

2

它會改變'this'是指什麼?

current不是this的別名,無論如何您都不能更改指針this

這是你在做什麼。假設this指向某個對象,並調用OBJECT1。在開始的時候,你有這樣的情況:

[ this --------> OBJECT1 ] (this points to OBJECT1) 

完此

TreeNode * current = this; 

你有這樣的情況:

[ this --------> OBJECT1 ] (this points to OBJECT1) 
[ current -----> OBJECT1 ] (current also points to OBJECT1) 

後你這樣做......

current = current->right; 

你有這種情況:

[ this --------> OBJECT1 ] (this still points to OBJECT1) 
[ current -----> OBJECT2 ] (current now points to a different object) 

OBJECT2是指向的對象或由OBJECT1->right

1

不,你是複製thiscurrent。更改current不會影響this。無論如何你都不能改變this的值。