2010-07-09 69 views
9

我用gcc 4.3.3嘗試編譯下面的代碼:嘗試插入到集合(C++)時,'operator <'不匹配?

struct testStruct { 
int x; 
int y; 
bool operator<(testStruct &other) { return x < other.x; } 
testStruct(int x_, int y_) { 
    x = x_; 
    y = y_; 
} 
}; 


int main() { 
multiset<testStruct> setti; 
setti.insert(testStruct(10,10)); 
return 0; 
} 

我得到這個錯誤:
/usr/include/c++/4.4/bits/stl_function.h|230|error :'__x < __y'
'運營商<'沒有匹配我懷疑我沒有按照應該完成的操作符重載,但我無法確定確切的問題。我在這裏做錯了什麼?

回答

13

操作人員必須是const,並採取一個const參考:

bool operator<(const testStruct &other) const { return x < other.x; } 
+0

謝謝你,解決它。 – tsiki 2010-07-09 16:24:55

+0

const方法的+1。 – 2011-10-18 18:27:47