改写要求:重载>>和<<实现分数类对象的直接输入输出,重载+完成多个分数对象加法
#include <cstdlib> #include <iostream> using namespace std; class Fract { int num,den; public: friend ostream& operator << (ostream& output,Fract& temp); friend istream& operator >> (istream& intput,Fract& temp1); Fract operator + (Fract& temp1); int gcd(int m,int n) { int r; if(m<n) { r=m;m=n;n=r; } while(r=m%n) { m=n; n=r; } return n; } }; istream& operator >>(istream& input,Fract& temp1) { input>>temp1.num>>temp1.den; return input; } ostream& operator <<(ostream& output,Fract& temp) { output<<temp.num<<"/"<<temp.den<<endl; return output; } Fract Fract::operator + (Fract& temp1) { Fract sum; int x,y,temp; x=num*temp1.den+den*temp1.num; y=den*temp1.den; temp=gcd(x,y); x=x/temp; y=y/temp; sum.num=x; sum.den=y; return sum; } int main(int argc, char *argv[]) { Fract temp1,temp2,temp; cin>>temp1>>temp2; temp=temp1+temp2; cout<<temp; system("PAUSE"); return EXIT_SUCCESS; }
时间: 2024-10-09 04:36:39