复数格式即实部+虚部。
在C++中是个练习运算符重载很好的例子,下面的代码给出了复数类中的基本运算。
重载了运算符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
//复数相关运算的运算符重载 #include <iostream> using namespace std; class Complex { private: double real; double image; public: Complex(){real=0;image=0;} Complex(double r,double i) { real=r; image=i; } void ShowComplex() { cout<<real; if(real>0) cout<<"+"; cout<<image<<"i"<<"\n"; } //重载 << friend ostream& operator <<(ostream &out,const Complex &c) { out<<c.real; if(c.real>0) out<<"+"; out<<c.image<<"i"<<"\n"; return out; } //重载 >> friend istream& operator >>(istream &in,Complex &c) { cout<<"input r:"<<endl; in>>c.real; cout<<"input i:"<<endl; in>>c.image; return in; } //重载 = Complex operator =(const Complex &c) { if(this == &c) return *this; //重要!防止自赋值导致低效 real=c.real; image=c.image; return *this; } //重载 -= Complex operator -=(const Complex &c2) { real-=c2.real; image-=c2.image; return *this; } //重载 +=(两个复数相加) Complex operator +=(const Complex &c2) { real+=c2.real; image+=c2.image; return *this; } //重载 +=(复数与实数相加) Complex operator +=(double c2) { real+=c2; return *this; } //重载 *= Complex operator *=(const Complex &c2) { real=real*c2.real-image*c2.image; image=image*c2.real+real*c2.image; return *this; } //重载/= Complex operator /=(const Complex &c2) { real=(real*c2.real+image*c2.image)/(c2.real*c2.real+c2.image*c2.image); image=(image*c2.real-real*c2.image)/(c2.real*c2.real+c2.image*c2.image); return *this; } //重载 +(复数相加) friend Complex operator +(const Complex &c1,const Complex &c2) { Complex c(c1); c+=c2; return c; } //重载 +(复数与实数相加) friend Complex operator +(const Complex &c1,double c2) { Complex c(c2,0); c+=c1; return c; } //重载 - friend Complex operator -(const Complex &c1,const Complex &c2) { Complex c(c1); c-=c2; return c; } //重载 * friend Complex operator *(const Complex &c1,const Complex &c2) { Complex c(c1); c*=c2; return c; } //重载 / friend Complex operator /(const Complex &c1,const Complex &c2) { Complex c(c1); c/=c2; return c; } }; int main() { Complex c; Complex c1(1.5,2.5); Complex c2(2.5,3.5); cout<<"c1:\t"; c1.ShowComplex(); cout<<"c2:\t"; c2.ShowComplex(); c=c1+c2; cout<<"c1+c2:\t"; c.ShowComplex(); cout<<"c1+5:\t"; c1+=5; c1.ShowComplex(); c=c1-c2; cout<<"c1-c2:\t"; c.ShowComplex(); c=c1*c2; cout<<"c1*c2:\t"; c.ShowComplex(); c=c1/c2; cout<<"c1/c2:\t"; c.ShowComplex(); cin>>c1; cout<<"c:"<<c1; return 0; } |
效果: