自定義類
class arc {
……
bool operator<(const arc& b) const;
}
用容器如vector,deque存放arc對象,再其上使用stl的algrithms中的sort算法:
sort(arcVector.begin(),arcVector.end());
方法中需要使用“<”作比較操作,故需要重載operator<
簡單重載 bool operator(arc&);
很可能報(bào)錯(cuò):
/usr/include/c++/4.2/bits/stl_algo.h:100: 錯(cuò)誤: no match 為‘operator<’在‘__b < __c’
主要是缺少const的限定(兩個(gè)都需要)。
否則有錯(cuò):
/usr/include/c++/4.2/bits/stl_algo.h:91: 錯(cuò)誤: 將‘const arc’作為‘bool arc::operator<(const arc&)’的‘this’實(shí)參時(shí)丟棄了類型限定
分析知道linux中stl下對C++的類型安全約束很強(qiáng),const保證導(dǎo)入對象和自身對象都不能被修改。
而stl的sort操作確實(shí)不需要修改比較的對象,也不應(yīng)該被修改,故強(qiáng)制使用的自定義operator<需要兩個(gè)const限制比較的兩個(gè)對象。
使用friend方法:
friend bool operator<(const arc&, const arc&);
兩種錯(cuò)誤:
1.friend bool operator<(const arc&, const arc&) const;
錯(cuò)誤: non-成員函數(shù)‘bool operator<(const arc&, const arc&)’不能擁有 cv 限定符
2.bool operator<(const arc&, const arc&) [const]
錯(cuò)誤: ‘bool arc::operator<(const arc&, const arc&) const’帶且僅帶 1 個(gè)實(shí)參