2010-05-04 68 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來包裝您的功能。你也可以編寫你自己的函子對象;在這種情況下,典型地從std::binary_function下降。 (請查看<functional>標題。)

12

typedef只給出了另一個類型的名稱。它確實不是創建一個截然不同類型。因此,實際上,您爲string超載operator <

如果你想創建一個獨特的類型,那麼你可以嘗試

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

,並與工作。

3

Typedef不能像這樣工作。 Typedef只是爲類型定義了一個別名 - 它仍然是一個字符串。爲了做到這一點,你需要一個新的類型。無論如何,你應該這樣做。您的操作員爲所有字符串重載比較運算符。