2011-03-16 2 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;                
} 

나는 CONST 다움을 캐스팅해야을 'this'포인터를 'next'에 할당 할 때 포인터가 'this'포인터의 값을 수정할 수있는 잠재력을 실제로 발생시킵니다. 항상 '다음'포인트가 무엇이든 수정하지 말 것을 상기시키는 것이 아니라 기능을보다 잘 설계함으로써 발생하지 않도록하는 방법이 있습니까? 당신이 내용을 수정하지 않으려면

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

답변

3

nextconst가합니다.

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

하지만이 경우에는 필요하지 않습니다.

+0

나는 const와 non-const 오브젝트 모두에서 작동하기를 원하기 때문에 메소드를 const로 만든다. 그리고 수정할 수없는 const 오브젝트의 결과와 non-const 오브젝트의 결과를 수정 가능하게하고 싶다. 함수의 반환 형식도 'const'라고 선언하면 비 const 객체의 경우에는 작동하지 않습니다. 아니면 두 가지 기능이 따로 있어야합니까? – zhanwu

+1

예, 두 가지 버전을 제공 할 수 있습니다. 하나의 const와 다른 non-const, 아니면 하나의 non-const 버전을 붙이십시오 (이것이 제가 선호하는 것입니다). – trojanfoe

+0

'const' 버전을 제공하는 것이 일반적인 패턴이며'non-const' 버전은 단순히 호출시 const_cast'const_cast'를 수행하고'non-const' 버전에서 리턴합니다. –

1

, 다음 min() 돌려 const 개체에 대한 포인터를해야한다 :

관련 문제