Http://acm.sdut.edu.cn/sdutoj/showproblem.php? PID = 2677 & cid = 1275 description
You can use this exercise to master the member Operator Overloading and friend Operator overloading.
It is required to define a plural class, And to reload addition and subtraction operators to meet the requirements for plural operations. The reload insertion operator (<) is used to output a plural value.
Input
The value of the object must be initialized when an object is created in the main function.
Output
There are 4 rows of output data, which respectively represent the values of A and B AND THEIR SUM and Difference values.
Sample Input
None
Sample output
a=3.2+4.5ib=8.9+5.6ia+b=12.1+10.1ia-b=-5.7-1.1i
Prompt
#include <iostream>using namespace std;class Complex{public: Complex(double r,double i) { rm=r; im=i; } friend Complex operator +(Complex &c1,Complex &c2); friend Complex operator -(Complex &c1,Complex &c2); void display();private: double rm,im;};void Complex::display(){ cout<<"="<<rm; if(im>=0) cout<<"+"<<im<<"i"<<endl; else cout<<im<<"i"<<endl;}Complex operator+(Complex &c1,Complex &c2){ return Complex(c1.rm+c2.rm,c1.im+c2.im);}Complex operator-(Complex &c1,Complex &c2){ return Complex(c1.rm-c2.rm,c1.im-c2.im);}int main(){ Complex c1(3.2,4.5),c2(8.9,5.6); Complex c3(0,0); cout<<"a"; c1.display(); cout<<"b"; c2.display(); cout<<"a+b"; c3=c1+c2; c3.display(); cout<<"a-b"; c3=c1-c2; c3.display(); return 0;}
4-1 operator overloading of complex classes (sdutoj2677)