2011-03-16 59 views
0

這是一個const成員函數,這讓我得到了樹的最小節點:如何設計const成員函數,防止它修改對象

BinarySearthTree* BinarySearchTree::min() const           
{                      
    // Return the minimum node (left-most node) value of the tree      
    BinarySearchTree * next = (BinarySearchTree *) this;        

    for (next ; next != NULL; next = next->pLeft)          
     if (next->pLeft == NULL)              
      return next;                
} 

我不得不推倒了常量性'this'指針指向'next'時,但這實際上提升了我可能修改'this'指向的值的潛力?與其總是提醒自己不要修改任何「下一個」要點,是否有辦法通過更好地設計功能來防止它發生?

回答

3

nextconst

const BinarySearthTree* BinarySearchTree::min() const           
{                      
    // Return the minimum node (left-most node) value of the tree      
    const BinarySearchTree *next;        

    for (next = this; next != NULL; next = next->pLeft)          
     if (next->pLeft == NULL)              
      return next; 
    return NULL;                
} 
+0

我讓方法爲const,因爲我希望它可以在const和非const對象上工作,並且我希望const對象的結果不可修改,並且可以修改非const對象的結果。如果我聲明函數的返回類型也是'const',那麼它就不適用於非const對象的情況。或者我應該分開兩個功能? – zhanwu 2011-03-16 11:07:37

+1

是的,你可以提供2個版本;一個常量和另一個非常量,或者只是堅持一個非常量版本(這將是我的偏好)。 – trojanfoe 2011-03-16 11:23:47

+0

這是一種常見的模式,只需提供'const'版本和'非const'版本就可以在調用中簡單地執行const_cast'const_cast',並從'非const'版本返回。 – 2011-03-16 12:57:20

1

如果您不希望要修改的內容做,那麼你應該min()返回一個指向const對象。

因此,您的next變量也應該是指向const對象的指針。

這裏是我想你的方法應該是:

const BinarySearchTree* BinarySearchTree::min() const 
{ 
    // Return the minimum node (left-most node) value of the tree 
    for (const BinarySearchTree* next = this; next != NULL; next = next->pLeft) 
    { 
     if (next->pLeft == NULL) 
     { 
      return next; 
     } 
    } 
    return this; 
} 

此外,在C++中,你應該避免C-風格的轉換。 const_cast用於此目的:

BinarySearchTree* next = const_cast<BinarySearchTree*>(this); 

但是在這種情況下,這不是必需的。