用C++实现复数类以及大整数类,主要是练习C++的运算符重载等知识。
复数类:
主要实现构造,重载+-运算符。
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 class Complex { 5 public: 6 double real; 7 double image; 8 Complex(double r=2.0,double i=-2.0); 9 Complex(const Complex& c); 10 11 //一元运算符推荐不用友元 12 Complex& operator += (const Complex& c); 13 Complex& operator -= (const Complex& c); 14 15 //二元运算符推荐用友元 16 friend bool operator == (const Complex& c1,const Complex& c2); 17 friend Complex operator + (const Complex& c1,const Complex& c2); 18 friend ostream& operator << (ostream& o,const Complex& c); 19 }; 20 21 Complex::Complex(double r,double i) : real(r),image(i) { } 22 Complex::Complex(const Complex& c) { 23 this->real=c.real; 24 this->image=c.image; 25 } 26 27 Complex& Complex::operator +=(const Complex& c) { 28 this->real+=c.real; 29 this->image+=c.image; 30 return *this; 31 } 32 33 Complex& Complex::operator -=(const Complex& c) { 34 this->real-=c.real; 35 this->image-=c.image; 36 return *this; 37 } 38 39 bool operator == (const Complex& c1,const Complex& c2) { 40 return (c1.real==c2.real && c1.image==c2.image); 41 } 42 43 Complex operator + (const Complex& c1,const Complex &c2) { 44 Complex ret(c1.real+c2.real,c1.image+c2.image); 45 return ret; 46 } 47 48 ostream& operator << (ostream& o,const Complex& c) { 49 o<<c.real<<" "<<c.image<<endl; 50 return o; 51 } 52 53 int main() 54 { 55 Complex c1; 56 Complex c2(3.0,-3.0); 57 Complex c3=c1; 58 cout<<"c1:"<<c1<<"c2:"<<c2<<"c3:"<<c3; 59 cout<<"c1==c2 ? "<<(c1==c2)<<endl; 60 cout<<"c1==c3 ? "<<(c1==c3)<<endl; 61 cout<<"c1+c2 : "<<(c1+c2); 62 63 c1+=c2; 64 cout<<"c1:"<<c1; 65 c1-=c3; 66 cout<<"c1:"<<c1; 67 return 0; 68 }
大整数类:
1 #include<bits/stdc++.h>
参考资料: