考慮下面的例子,行int a = objT + 5;
給出了模棱兩可的轉換,它使用兩種方式處理,使用我認爲不需要的顯式轉換,並用成員函數替換轉換運算符的使用。在這裏,我的問題變成了你仍然使用轉換操作符還是根本不使用轉換操作符?何時使用轉換運算符?
class Testable {
public:
Testable(int val = 0):x(val){}
operator int() const { return x; }
operator double() const { return x; }
int toInt() { return x; }
double toDouble() { return x; }
private:
int x;
};
int main()
{
Testable objT(10);
// ambiguous conversion
int a = objT + 5;
// why to use explicit cast when
// the conversion operator is for to handle
// this automatically
int b = static_cast<int>(objT) + 5;
// member functions
int c = objT.toInt() + 5;
}
所以,我認爲現在歸結爲有一個轉換函數爲int或double和一個成員函數爲轉換的其他選擇取決於類的數據成員。或者我可以完全擺脫轉換運營商,以避免任何明確的轉換。 – cpx