重载全部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;
}
stn和lbs分别是什么,Stonewt对象判断的依据是什么,这个题目无非就是要求你重载> >= < <= == !=6个运算符。
先不说你发的代码的内容,C++中运算符重载也算常见,一本C++ primer基本就可以解决大多数的问题,运算符重载在书中也有明确的讲解
2stn 0.5lbs.
3stn 8.1lbs.
1stn 2.1lbs.
2stn 6lbs.
12stn 0.4lbs.
12stn 0.6lbs.
max 12stn 0.6lbs.
mix 1stn 2.1lbs.
11 stone: 2
Press any key to continue
Stonew类 内部重载需要用到的 运算符 运算符
对比 pounds 值 返回 bool结果
剩下的就是 外部 冒泡法