/*代码如下*/
1 #include "pch.h" 2 #include <iostream> 3 using namespace std; 4 5 class Complex { 6 public: 7 Complex(double r = 0.0, double i = 0.0) :real(r), imag(i){} 8 Complex operator+(const Complex &x); 9 void print(); 10 friend Complex operator-(const Complex &c1, Complex &c2); 11 private: 12 double real; 13 double imag; 14 }; 15 16 Complex Complex::operator+(const Complex &x) { 17 return Complex(real + x.real, imag + x.imag); 18 } 19 20 void Complex::print() { 21 if (real == 0) 22 cout << imag << "i" << endl; 23 else if(imag == 0) 24 cout << real << endl; 25 else 26 cout << real << "+" << imag << "i" << endl; 27 } 28 29 Complex operator-(const Complex &c1, Complex &c2) { 30 return Complex(c1.real - c2.real, c1.imag - c2.imag); 31 } 32 33 int main() { 34 Complex c1(2, 2.5); 35 cout << "c1="; 36 c1.print(); 37 Complex c2(4.5); 38 cout << "c2="; 39 c2.print(); 40 Complex c3; 41 c3 = c1 + c2; 42 cout << "c1+c2="; 43 c3.print(); 44 c3 = c1 - c2; 45 cout << "c1-c2="; 46 c3.print(); 47 return 0; 48 }
/*运行截图*/