我想用我的class
作爲key
在map
,所以我超載operator+
。如果我將它作爲朋友函數進行超載,它會很好用。當我將它作爲類中的成員函數進行重載時,會導致編譯錯誤。小於運營商不能超載爲會員功能
error C2678: binary '<': no operator found which takes a left-hand operand of type 'const Syl' (or there is no acceptable conversion)'.
在細節,這並不編譯,生成編譯錯誤:
Syl.h
bool operator< (const Syl& rhs);
Syl.cpp
bool Syl::operator< (const Syl& rhs) { return false; }
這枚編譯。
Syl.h
friend bool operator< (const Syl& lhs, const Syl& rhs);
Syl.cpp
bool operator< (const Syl& lhs, const Syl& rhs) { return false; }
我不知道爲什麼。我知道運算符<是二進制的,但無論如何要將它重載爲函數成員?
由於重載解析和隱式轉換的工作方式,「朋友」版本無論如何都是一個更好的主意。 –
友好版本規定,兩個操作數都是'const',另一個版本只說輸入參數是'const'。您必須將方法標記爲這樣...您必須仔細閱讀錯誤,特別注意「const」,「signed」等單詞的含義。 – Kupto