實驗二 自定義類型的運算
【實驗目的】
- 理解運算符函數與運算符重載方法;
- 掌握運算符重載為友元函數;
【實驗內容】
題目:
在C++中,分數不是預先定義的,建立一個分數類,使之具有以下功能:能防止分母為0、當分數不是最簡形式時進行約分及分母為負數。用重載運算符完成加法、減法、乘法、除法等四則運算。
源程序代碼:
#include<iostream>
#include<cstdlib>
using namespace std;
int gcd(int m,int n)//求最大公約數函數
{
if (m < n)
{
int tmp = m;
m = n;
n = tmp;
}
if (n == 0)
return m;
else
return gcd(n,m % n);
}
class fraction //構建分數類
{
int a,b;
public:
fraction(int x=0,int y=1) //構造函數
{
if(y==0) //判斷分母是否為0
{
cout<<"分母為零"<<endl;
exit(0);
}
if(y<0) //分母小於0時將負號轉移到分子上
{
a=(-1)*x;
b=(-1)*y;
}
a=x;
b=y;
}
fraction(const fraction&f)//拷貝構造
{
a=f.a;
b=f.b;
}
~fraction(){}//析構函數
void setfraction(int x,int y)//在類外重新設置分數值
{
if(y==0)
{
cout<<"分母為零"<<endl;
exit(0);
}
if(y<0)
{
a=(-1)*x;
b=(-1)*y;
}
a=x;
b=y;
}
void show()//輸出最簡結果
{
int flag=1,m;
if(a<0)
{
a=-a;
flag=-flag;
}
if(b<0)
{
b=-b;
flag=-flag;
}
m=gcd(a,b);
a=a/m;
b=b/m;
a=a*flag;
if(a==0||b==1)
cout<<a<<endl;
else
cout<<a<<"/"<<b<<endl;
}
friend fraction operator + (fraction & f1,fraction & f2 ) //以友元函數重載運算符
{
return fraction(f1.a * f2.b + f1.b * f2.a , f1.b * f2.b);
}
friend fraction operator - (fraction & f1,fraction & f2)
{
return fraction(f1.a*f2.b-f1.b*f2.a,f1.b*f2.b);
}
friend fraction operator * (fraction & f1,fraction & f2)
{
return fraction(f1.a*f2.a,f1.b*f2.b);
}
friend fraction operator / (fraction & f1,fraction & f2)
{
return fraction(f1.a*f2.b,f1.b*f2.a);
}
};
int main()
{
int a,b;
cout<<"請輸入第一個分數的分子分母"<<endl;
cin>>a>>b;
int c,d;
cout<<"請輸入第二個分數的分子分母"<<endl;
cin>>c>>d;
fraction a1,a2,a3,a4,a5,a6;
a1.setfraction(a,b);
a2.setfraction(c,d);
a3=a1+a2;
cout<<"加法結果"<<endl;
a3.show();
a4=a1-a2;
cout<<"減法結果"<<endl;
a4.show();
a5=a1*a2;
cout<<"乘法法結果"<<endl;
a5.show();
a6=a1/a2;
cout<<"除法法結果"<<endl;
a6.show();
return 0;
}
運行結果截圖:
【實驗小結】
- 在運算完成后輸出所需結果時進行約分,使之輸出最簡結果;
- 可以將化簡部分寫一個單獨的函數來使用;
- 在重載運算符的時候再運算符前后打上空格使格式好看。