重載全部6個關系運算符,運算符對pounds成員進行比較,並返回一個bool值,編程,它聲明一個包含6個Stonewt對象的數組,並在數組聲明中初始化前3個對象。然後使用循環來讀取用於設置剩余3個數組元素的值。接著報告最小的元素,最大的元素以及大於或等於11英石的元素的數量。
#include <iostream>
using namespace std;
class Stonewt
{
private:
int stone;
double pounds;
public:
Stonewt()
{
stone = 0;
pounds = 0.0;
}
Stonewt(double lbs)
{
stone = (int)lbs / 14;
pounds = lbs - ((int)lbs / 14 * 14);
}
Stonewt(int stn, double lbs)
{
stone = stn + (int)lbs / 14;
pounds = lbs - ((int)lbs / 14 * 14);
}
void show()
{
cout << stone << "stn " << pounds << "lbs." << endl;
}
bool operator > (const Stonewt &s)
{
if (stone == s.stone)
return pounds > s.pounds;
else
return stone > s.stone;
}
bool operator < (const Stonewt &s)
{
if (stone == s.stone)
return pounds < s.pounds;
else
return stone < s.stone;
}
bool operator == (const Stonewt &s)
{
if (stone == s.stone)
return pounds == s.pounds;
else
return false;
}
bool operator >= (const Stonewt &s)
{
return *this > s || *this == s;
}
bool operator <= (const Stonewt &s)
{
return *this < s || *this == s;
}
bool operator != (const Stonewt &s)
{
return !(*this == s);
}
};
int main()
{
Stonewt arr[6] = { Stonewt(28.5), Stonewt(50.1), Stonewt(1, 2.1) };
arr[3] = Stonewt(1, 20.0);
arr[4] = Stonewt(12, 0.4);
arr[5] = Stonewt(12, 0.6);
Stonewt max = arr[0];
Stonewt min = arr[0];
int n = 0;
Stonewt c = Stonewt(11, 0.0);
for (int i = 0; i < 6; i++)
{
arr[i].show();
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
if (arr[i] >= c) n++;
}
cout << "max "; max.show();
cout << "mix "; min.show();
cout << "> 11 stone: " << n << endl;
return 0;
}