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