2011-03-16 58 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); 

但是在这种情况下,这不是必需的。