一個類適應 STL 模板的基礎條件的討論

class aClass
{
public:
aClass(); //默認構造函數
aClass(const aClass& temp); //複製構造函數
~aClass(); //析構函數
aClass& operator = (const aClass& temp); //賦值運算符
 bool operator < (const aClass& temp) const ; 
};



特別注意  <  運算符的const修飾符不能夠忘記,因爲在STL模板庫中 

經常會用到謂詞 less<T>()

template<class _Ty>
	struct less
		: public binary_function<_Ty, _Ty, bool>
	{	// functor for operator<
	bool operator()(const _Ty& _Left, const _Ty& _Right) const
		{	// apply operator< to operands
		return (_Left < _Right);
		}
	};

bool operator()(const _Ty& _Left, const _Ty& _Right) const
這裏對兩個參數的要求都是 const 加 引用類型  ,

如果不加const 則會報錯: error C2678: 二進制“<”: 沒有找到接受“const Person”類型的左操作數的運算符(或沒有可接受的轉換)


同樣的,編寫  getXXX() 函數的時候,也要加上 const  修飾

例如:

string getName() const {return name;}

如果不加上const 則會報錯 error C2662: “Person::getName”: 不能將“this”指針從“const Person”轉換爲“Person &”



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章