2023.4.18
1 //例8.1 2 #include <iostream> 3 using namespace std; 4 class Complex 5 { 6 public: 7 Complex(double r = 0.0,double i = 0.0):real(r),image(i){} 8 Complex operator+(const Complex &c2) const; 9 Complex operator-(const Complex &c2) const; 10 void display() const; 11 private: 12 double real; 13 double image; 14 }; 15 Complex Complex::operator+(const Complex &c2) const 16 { 17 return Complex(real+c2.real,image+c2.image); 18 } 19 Complex Complex::operator-(const Complex &c2) const 20 { 21 return Complex(real-c2.real,image-c2.image); 22 } 23 void Complex::display()const 24 { 25 cout<<"("<<real<<","<<image<<")"<<endl; 26 } 27 int main() 28 { 29 Complex c1(5,4),c2(2,10),c3; 30 cout<<"c1 = ";c1.display(); 31 cout<<"c2 = ";c2.display(); 32 c3 = c1 -c2; 33 cout<<"c3 = c1 - c2 = ";c3.display(); 34 c3 = c1 + c2; 35 cout<<"c3 = c1 + c2 =";c3.display(); 36 return 0; 37 }