2012-12-18 8 views
2

constbool operator<(const Node& otherNode) //const에 넣지 않으면 오류가 발생하는 이유는 무엇입니까?C++ 오버로드 연산자 <오류

stl_algo.h:91: error: passing 'const Node' as 'this' argument of 'bool Node::operator<(const Node&)' discards qualifiers 

모든 오버로드 된 연산자는 일정해야합니까?

class Node { 
public: 
    double coordinate; 

    bool operator==(const Node& other) const{ 
     return coordinate == other.coordinate; 
    } 

    bool operator<(const Node& other) const{ 
     return coordinate < other.coordinate; 
    } 
}; 

답변

6

모든 사업자하지만 ==< 확실히 예, const을해야한다. 논리적으로 비교할 개체를 수정하지 않습니다.

오류 가능성 예, const 하나 비 const 메소드 호출에서 유래

: 또한 따라서, 방법 isSmallerconst 때문에, this는 암시 const 목적이 경우

bool isSmaller(const Node& other) const 
{ 
    return *this < other; 
} 

, operator <을 해당 컨텍스트 내에서 호출이 유효하도록하려면 const이어야합니다. 오류 메시지에서

, 그것은 Node::operator <stl_algo.h에 함수에서하는 const 객체에 호출되는 것 같습니다 - 기능을 해시 함수 주문/정렬 등

+0

작동했지만 모든 운영자가 const 여야 만하는지 의심 스러웠습니다. 지금은 이해. 감사. – BRabbit27

1

비교 연산자와 같은 <, >, <=, >=, ==, !=은 일반적으로 const 개체에서 작동해야합니다. 이는 비교되는 개체가 비교에 의해 변경 될 수 있기 때문에 의미가 없기 때문입니다. 그러나 두 피연산자 사이의 대칭성을 보장하기 위해 비 멤버 함수로 비교를 선언 할 수 있습니다.

class Node { 
public: 
    double coordinate; 
}; 
inline operator<(const Node& lhs, const Node& rhs) 
{ 
    return lhs.coordinate < rhs.coordinate; 
} 
+0

왜 downvote? – juanchopanza

0

메서드의 const 한정자를 삭제하려고 했습니까? @LuchianGrigore가 있습니다 sugest으로 또한, 당신은 this 키워드를 사용할 수 있습니다

내가 프로그래밍에 대한 퀴즈를 가진 한 후 나는 비교 연산자 오버로딩이 작동되지 않았기 때문에 나는 그냥 CONST를 넣어, 당황과 예
bool operator< (const Node& other) { 
    return this.coordinate < other.coordinate; 
} 
+0

예'const'를 넣지 않으면 오류가 발생하는 반면, 넣으면 올바르게 동작합니다. 연산자가 모든 const 함수가되어야 하는지를 알고 싶었습니다. – BRabbit27

+0

나는 그것을 위해 const로 메서드를 선언 한 적이 없다. 왜이 오류가 발생하는지 이해가 안됩니다. 이것 좀보세요 : http://www.cplusplus.com/doc/tutorial/classes2/ – adripanico

+0

@ LuchianGrigore의 답변을 읽어보십시오. – BRabbit27