题目: 定义三角形类,该类有两个私有的数据成员底和高。要求重载>,<,>=,<=,!=, == 6个运算符,能比较两个三角形面积的大小。编写主函数进行测试。
#include<iostream>
#include<iomanip>
using namespace std;
class A
{double ch; //长
double ku; //宽
public:
double s;
A(double c,double k){ch=c;ku=k;s=c*k/2.0;} //初始化赋值
bool operator<(const A&c);
bool operator>(const A&c);
bool operator>=(const A&c);
bool operator<=(const A&c);
bool operator!=(const A&c);
bool operator==(const A&c); //成员函数重载运算符
};
bool A::operator<(const A& c) //此时的参数是另一个比较对象
{
if(s<c.s)return true; //面积比较 本身为s令一个为c.s
else return false;}
bool A::operator>(const A& c)
{
if(s>c.s)return true;
else return false;}
bool A::operator>=(const A& c)
{
if(s>=c.s)return true;
else return false;}
bool A::operator<=(const A& c)
{
if(s<=c.s)return true;
else return false;}
bool A::operator!=(const A& c)
{
if(s!=c.s)return true;
else return false;}
bool A::operator==(const A& c)
{
if(s==c.s)return true;
else return false;}
int main(){
double c1,k1,c2,k2;
cin>>c1>>k1>>c2>>k2;
A s1(c1,k1);
A s2(c2,k2);
if(s1<s2){cout<<fixed<<setprecision(2)<<s1.s<<endl;
cout<<fixed<<setprecision(2)<<s2.s<<endl;}
if(s1>s2){cout<<fixed<<setprecision(2)<<s2.s<<endl;
cout<<fixed<<setprecision(2)<<s1.s<<endl;}
}
可以看出下面的输出格式(没有空格),和小数使用方法错误(顺序)
int main(){
double c1,k1,c2,k2;
cin>>c1>>k1>>c2>>k2;
A s1(c1,k1);
A s2(c2,k2);
if(s1<s2){cout<<s1.s<<fixed<<setprecision(2)<<" "<<s2.s<<fixed<<setprecision(2)<<endl;}
if(s1>s2){cout<<s2.s<<fixed<<setprecision(2)<<" "<<s1.s<<fixed<<setprecision(2)<<endl;}
}
当你定义运算面积的成员函数时;就需要调用该函数才能为面积赋值
主函数中
另一种** //**
在bool函数定义时
return s>b.s
并没有进行true 或者false的输出
而在主函数中的判断
if(a>b){
cout<<fixed<<setprecision(2)<<b.s<<endl;
cout<<fixed<<setprecision(2)<<a.s<<endl;}
()中的a>b;就是调用重载运算符;a>b即return 值s>b.s
再通过if语句判断s是否大于b.s