#include <iostream> using namespace std; int GreatestCommonDivisor(int m,int n) //輾轉相除法求最大公約數 { int r; do { r = m % n; m = n; n = r; } while ( r != 0 ); return m; } class Fraction; // ostream& operator<<(ostream& out,const Fraction &fra); // istream& operator>>(istream& in,const Fraction& fra); //此三行為滿足vc6.0的編譯邏輯而聲明 class Fraction{ private: int fenzi,fenmu; //分子,分母 public: Fraction(){} ~Fraction(){} Fraction(int fenzi,int fenmu); Fraction operator+(const Fraction &fra)const; Fraction operator-(const Fraction &fra)const; Fraction operator*(const Fraction &fra)const; Fraction operator/(const Fraction &fra)const; friend ostream& operator<<(ostream& out,const Fraction& fra);//i/o重載必須使用友元重載 friend istream& operator>>(istream& in,const Fraction& fra); void setValue(int mu,int zi); }; Fraction::Fraction(int zi,int mu):fenzi(zi),fenmu(mu){ if(mu==0){ cout<<"分母不能為0!"<<endl; exit(0); } } ostream& operator<<(ostream& out,const Fraction &fra){ if(fra.fenmu<0) out<<"(-"<<fra.fenzi<<"/"<<-fra.fenmu<<")"; //負分數顯示 else if(fra.fenzi<0) out<<"(-"<<-fra.fenzi<<"/"<<fra.fenmu<<")"; else if(fra.fenmu==1) out<<fra.fenzi; //整數顯示 else out<<fra.fenzi<<"/"<<fra.fenmu; //正分數顯示 return out; } istream& operator>>(istream& in, Fraction& fra){ int mu,zi; cout<<"請輸入分母與分子"<<endl; in>>mu>>zi; fra.setValue(mu,zi); return in; } void Fraction::setValue(int mu,int zi){ fenmu=mu; fenzi=zi; } Fraction Fraction::operator+(const Fraction &fra)const{ int a=fenzi,b=fenmu; //▲▲▲重點▲▲▲ //一定要使用const,因為不用的話會使上次運算的數據賦值到下次的運算l-value中 //因為const函數無法改變類的內部變量,所以要用替身,若此處重載改用friend重載 //則可以有效地避免此問題,因為friend重載的操作符有兩個引用的參數 a=fra.fenmu*fenzi+fra.fenzi*fenmu; b*=fra.fenmu; int g=GreatestCommonDivisor(a,b); if (g!=1) { a/=g; b/=g; } return Fraction(a,b); } Fraction Fraction::operator-(const Fraction &fra)const{ int a=fenzi,b=fenmu; a=fra.fenmu*fenzi-fra.fenzi*fenmu; b*=fra.fenmu; int g=GreatestCommonDivisor(a,b); if (g!=1) { a/=g; b/=g; } return Fraction(a,b); } Fraction Fraction::operator*(const Fraction &fra)const{ int a=fenzi,b=fenmu; a*=fra.fenzi; b*=fra.fenmu; int g=GreatestCommonDivisor(a,b); if (g!=1) { a/=g; b/=g; } return Fraction(a,b); } Fraction Fraction::operator/(const Fraction &fra)const{ return *this*Fraction(fra.fenmu,fra.fenzi); } void main() { Fraction a(1,2); Fraction b(1,4); Fraction c=a+b; Fraction d=a-b; Fraction e=b-a; Fraction f=a*b; Fraction g=a/b; cout<<"a=1/2"<<endl <<"b=1/4"<<endl <<"a+b="<<c<<endl <<"a-b="<<d<<endl <<"b-a="<<e<<endl <<"a*b="<<f<<endl <<"a/b="<<g<<endl; Fraction h; cin>>h; cout<<h<<endl; }