1 //class_head.h 2 class Complex 3 { 4 public: 5 Complex() 6 {molecules=0;denominator=0;} 7 Complex(int n,int m);//对运算符的重载,c3默认会传第二个操作数的值,所以只要写一个参数//也可以这样的写法 Complex operator+(Complex &c2); 8 Complex operator+(Complex c3); 9 Complex operator-(Complex c3); 10 Complex operator*(Complex c3); 11 Complex operator/(Complex c3); 12 Complex input(Complex &c);//实现对私有成员的赋值操作 13 void output(); 14 private: 15 int molecules; 16 int denominator; 17 void simplification();//化简 18 };
//class_yuan.cpp #include<iostream> using namespace std; #include "class_head.h" #include<cmath> Complex::Complex(int n,int m) { molecules=n,denominator=m; simplification(); }//使用了欧几里得算法(辗转相除法)利用两个数的公约数对于较小数与两数之间的余数的公约数 void Complex::simplification() { if(denominator<0) { molecules=-molecules; denominator=-denominator; } int a=abs(molecules);//abs()是取绝对值,包含在头文件<cmath>里面 int b=abs(denominator); while(b>0) { int t=a%b; a=b; b=t; } molecules=molecules/a; denominator=denominator/a; } Complex Complex::operator+(Complex c3) { int a=molecules; int b=denominator; int c=c3.molecules; int d=c3.denominator; int e=a*d+b*c; int f=b*d; return Complex(e,f); } Complex Complex::operator-(Complex c3) { c3.molecules=-c3.molecules; return operator+(c3); } Complex Complex::operator*(Complex c3) { int a=molecules; int b=denominator; int c=c3.molecules; int d=c3.denominator; int e=a*c; int f=b*d; return Complex(e,f); } Complex Complex::operator/(Complex c3) { int t=c3.molecules; c3.molecules=c3.denominator; c3.denominator=t; return operator*(c3); } Complex Complex::input(Complex &c) { int a,b; cout<<"输入分子 "; cin>>a; cout<<"输入分母 "; cin>>b; molecules=a; denominator=b; return c; } void Complex::output() { if(molecules%denominator==0) cout<<molecules/denominator; else cout<<molecules<<"/"<<denominator; }
//main() #include<iostream> using namespace std; #include "class_head.h" int main() { int i; Complex c1,c2,c3; cout<<"¥¥输入第一个操作数¥¥"<<endl; c1.input(c1); cout<<"¥¥输入第二个操作数¥¥"<<endl; c2.input(c2); cout<<"请选择要进行的操作"<<endl; cout<<"1表示+法"<<endl; cout<<"2表示-法"<<endl; cout<<"3表示*法"<<endl; cout<<"4表示/法"<<endl; cin>>i; switch(i) { case 1: c3=c1+c2; cout<<"进行加法之后的结果为:"<<endl; cout<<"结果等于:"; c3.output(); cout<<endl; break; case 2: c3=c1-c2; cout<<"进行减法之后的结果为:"<<endl; cout<<"结果等于:"; c3.output(); cout<<endl; break; case 3: c3=c1*c2; cout<<"进行乘法之后的结果为:"<<endl; cout<<"结果等于:"; c3.output(); cout<<endl; break; case 4: c3=c1/c2; cout<<"进行除法之后的结果为:"<<endl; cout<<"结果等于:"; c3.output(); cout<<endl; break; } return 0; }
原文地址:https://www.cnblogs.com/chenzinumber1/p/8275008.html
时间: 2024-10-19 04:19:50