2010-05-04 5 views
3

나는이 있습니다재귀 문제 과부하 운영자

typedef string domanin_name; 

을 그리고,이 방법으로 운영자 < 과부하하려고 :

bool operator<(const domain_name & left, const domain_name & right){ 
    int pos_label_left = left.find_last_of('.'); 
    int pos_label_right = right.find_last_of('.'); 

    string label_left = left.substr(pos_label_left); 
    string label_right = right.substr(pos_label_right); 
    int last_pos_label_left=0, last_pos_label_right=0; 

    while(pos_label_left!=string::npos && pos_label_right!=string::npos){ 
     if(label_left<label_right) return true; 
     else if(label_left>label_right) return false; 

     else{ 
      last_pos_label_left = pos_label_left; 
      last_pos_label_right = pos_label_right; 

      pos_label_left = left.find_last_of('.', last_pos_label_left); 
      pos_label_right = right.find_last_of('.', last_pos_label_left); 

      label_left = left.substr(pos_label_left, last_pos_label_left); 
      label_right = right.substr(pos_label_right, last_pos_label_right); 
     } 
    } 
} 

을 나는 그것이 연산자를 오버로드하는 이상한 방법을 알고 <하지만이 방법으로해야합니다. 그것은 내가 원하는 것을해야합니다. 그것은 요점이 아니다.

문제는 그것이 바로이 라인에 무한 루프에 입력하는 것입니다 :

if(label_left<label_right) return true; 

그것은을 비교 한을이 오버로딩 기능 자체를 사용하려고 것 같아,하지만 문자열이 label_left입니다, 아니 도메인 이름!

의견이 있으십니까?

답변

1

귀하의 typedef는 새로운 유형을 생성하지 않습니다. 이전과 같은 유형을 참조하는 새 이름을 만듭니다. 따라서 두 문자열에서 연산자 함수 내에 <을 사용하면 컴파일러는 인수 유형이 일치하기 때문에 컴파일하는 연산자와 동일한 연산자를 사용합니다.

bool domain_less(domain_name const& left, domain_name const& right); 

는 다음과 같은 std::sort 같은 비교 함수에 대한 호출 장소에서 해당 기능을 사용 대신 할 수도 있습니다 무엇

는 완전히 새로운 함수를 정의합니다. 대부분의 표준 알고리즘은 기본적으로 <을 사용하지만 대신 자신의 술어 기능을 제공 할 수 있습니다. 함수를 랩핑하려면 std::ptr_fun을 사용해야 할 수도 있습니다. 당신은 또한 당신 자신의 Functor 객체를 작성할 수있다; 이 경우에는 std::binary_function에서 내려 오는 것이 일반적입니다. (<functional> 헤더를 확인하십시오.)

12

은 유형에 대해 다른 이름을 제공합니다. 이 아닌 유형을 만듭니다. 따라서 실질적으로 string에 대해 operator <이 오버로드되고 있습니다. 당신이 구별 유형을 만들려면

, 당신은

struct domain_name { 
    string data; 
    // ... 
}; 

을 시도하고 그와 함께 작업 할 수 있습니다.

3

Typedef는 이와 같이 작동하지 않습니다. Typedef는 단순히 유형에 대한 별칭을 정의합니다. 이는 여전히 문자열입니다. 이렇게하려면 새로운 유형이 필요합니다. 어쨌든이 작업을 수행해야합니다. 연산자가 모든 문자열에 대해 비교 연산자를 오버로드하고 있습니다.