三角形_運算符重載

在這裏插入圖片描述
題目: 定義三角形類,該類有兩個私有的數據成員底和高。要求重載>,<,>=,<=,!=, == 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章