在看lftp的原始碼的時候,發現這麼一行:
operator bool() const { return ... }
一下子沒想起來,這是什麼文法,是operator overload嗎?不像阿,怎麼不以函數的傳回值打頭呢?後來一查C++ Primer,明白了,這是convert operator,也就是將這個類如果要轉化成bool值的話,就會調用到這個函數。convert operator以operator關鍵字打頭,緊跟類型,然後是兩個括弧(括弧中不能帶有參數)。更具體的看C++ Primer和上面的注釋。
不過看明白了之後有個問題:
operator int() const { ...... }
bool operator<(int input) { ...... }
就是如果這兩個operator都定義了(一個是convert op, 一個是arithmetic op),那麼,在實際代碼中會用到哪個呢?為此,寫了一小段測試代碼:
-
Code: Select all
-
#include <iostream>
using namespace std;class A {
public:
operator int() const { cout << "INT Convert function called..." << endl; return content; }
bool operator<(int input) {
cout << "Less operator function called..." << endl;
if (content < input)
return true;
else
return false;
}
void setContent(int value) { content = value; }
private:
int content;
};
int main()
{
A a;
a.setContent(10);
if (a < 100)
cout << "Class A is less than 100..." << endl;
else
cout << "Class A is larger than 100..." << endl;
cout << "The abs of class A is: " << abs(a) << endl;
return 0;
}
測試結論是,第一個調用:if (a < 100),調用的是arithmetic op;第二個調用abs(a),使用的是convert op。所以,現在有答案了:
1. 當有精確匹配時,比如a < 100這種,肯定使用精確匹配。因為如果使用convert op將a變成int,然後比較的話,要經過一個convert的過程;< operator這個函數是精確匹配,所以,肯定用這個。
2. 第二個調用無法使用arithmetic op,所以,只能用convert op,將a轉化成int。在實際編碼過程中,除了這種情況,還有一些情況也會用到convert op。比如,class就定義了< operator,沒定義>,那麼,碰到if (a > 100)這種的時候,就只能使用convert op了。
3. 避免出現ambiguous的情況。比如,如果我們代碼這樣寫:if (a < 100.00),那麼,編譯就無法通過了。因為如果使用arithmetic op,那麼,需要將100.00轉化成int,才滿足arithmetic op的參數要求;但是如果使用convert op,也需要將產生的int轉化成double,才能和100.00做比較。這樣一來,編譯器就無法分辨這兩種方案的優先順序了,自然編譯就會出錯了。
OK, That's all.