這裏我試圖重載關係運算符。當我米appyling重載函數類的兩個對象然後它是工作,但是當I M把它應用到一個對象和浮點值然後它給我錯誤,指出「從「double'to‘距離’轉換ambigous」。 請幫忙。如何使用用戶定義的數據類型對定義的數據類型進行操作?
#include <iostream>
using namespace std;
class Distance
{
int iFeet;
float fInches;
public:
Distance(const float);
Distance(const int = 0, const int = 0);
bool operator >(const Distance);
};
Distance::Distance(const float p)
{
iFeet = int(p);
fInches = (p - iFeet) * 12;
}
Distance::Distance(const int a, const int b)
{
iFeet = a;
fInches = b;
}
bool Distance::operator>(const Distance dd1)
{
if (iFeet > dd1.iFeet)
return true;
if (iFeet == dd1.iFeet && fInches > dd1.fInches)
return true;
return false;
}
int main()
{
Distance D(1, 6), D2(1, 8);
if (D > D2)
cout << "D is gtreater than D2" << endl;
else
cout << "D2 is greater than D" << endl;
if (D > 5.6)
cout << "D is greateer" << endl;
else
cout << "D is not greater" << endl;
return 0;
}