在VS2015中定義了這樣一個類:
#include<iostream> #include<vector> #include<string> using namespace std; class Integer { public : int num = 0; Integer(int num) { this->num = num; } Integer() { Integer(0); } bool operator< (const Integer& lh, const Integer& rh) { return rh.num < lh.num; } };
對於重載的 < 運算符,顯示如下錯誤:
網上查找原因,解釋如下:
1.你為Book類定義operator==作為成員函數,所以它有一個隱式的Book*參數this指針
2. 一個雙目運算符重載應該在類定義之外。 class Book { ... }; bool operator==(const Book& a, const Book & b) { return a.Return_ISBN()==b.Return_ISBN(); }
重新如下定義就對了:
#include<iostream> #include<vector> #include<string> using namespace std; class Integer { public : int num = 0; Integer(int num) { this->num = num; } Integer() { Integer(0); } }; //雙目運算符重載定義在類外 bool operator< (const Integer& lh, const Integer& rh) { return rh.num < lh.num; }
如果必須要在類內定義的話,只能定義為單參數的運算符函數:
#include<iostream> #include<vector> #include<string> using namespace std; class Integer { public : int num = 0; Integer(int num) { this->num = num; } Integer() { Integer(0); } bool operator< (const Integer& rh) { return rh.num < this->num; //this指針作為默認參數傳入該函數 } };
此時,如果在源文件中定義了如下的模板函數:
template<typename T> int compare(const T& a,const T& b) { if (a < b) return -1; if (b < a) return 1; return 0; }
則該模板函數只接受類外定義的雙目運算符:
bool operator< (const Integer& lh, const Integer& rh) { return rh.num < lh.num; }
而類內定義的單參數運算符
bool operator< (const Integer& rh) { return rh.num < this->num; //this指針作為默認參數傳入該函數 }
會被報錯。