Object-Oriented Programming Practice 10 (Operator overloading) Time Limit: 1000 ms memory limit: 65536 K The topic description defines a complex class complex, which can be used by the "+" operator to add a complex number. The calculation amount can be a class object or an integer, with any order. For example, C1 + C2, I + C1, and C1 + I are valid. (Where I is an integer, C1, C2 is a plural number), programming to calculate the sum of two plural numbers, the sum of integers and plural numbers. There are three input rows: the fifth row is the real part and the virtual part of the 1st plural C1, separated by spaces. The fifth row is the real part and the virtual part of the 2nd plural C2, separated by spaces. The first row is the value of 1 integer I. There are three output rows:
The second row contains the sum of two plural numbers C1 and C2. The display method is: real part + virtual Part I
Row 2nd is the value of 1st plural numbers C1 plus I. Display Method: real part + virtual Part I
Row 3rd is the value of I plus 1st plural C1 values. Display Mode: real part + virtual Part I sample input
2 33 510
Sample output
5+8i12+3i12+3i
Source
This question is almost the same as the previous one. Http://blog.csdn.net/u013634961/article/details/40189475
#include <iostream>using namespace std;class Complex{private: int real; int imag;public: Complex() { real=0; imag=0; } Complex(int x,int y) { real=x; imag=y; } Complex operator+( Complex r); Complex operator+(int r); friend Complex operator+(int , Complex ); friend ostream &operator <<(ostream &, Complex &);};Complex Complex :: operator+( Complex r){ Complex d; d.real=real+r.real; d.imag=imag+r.imag; return d;}Complex Complex :: operator+(int r){ Complex d; d.real=real+r; d.imag=imag; return d;}Complex operator+(int x, Complex r){ Complex d; d.real=x+r.real; d.imag=r.imag; return d;}ostream&operator<<(ostream&output, Complex &c){ output<<c.real<<"+"<<c.imag<<"i"; return output;}int main(){ int a,b,c,d,e; cin>>a>>b>>c>>d>>e; Complex r1(a,b); Complex r2(c,d); Complex r3; r3=r1+r2; cout<<r3<<endl; r3=r1+e; cout<<r3<<endl; r3=e+r1; cout<<r3<<endl; return 0;}
Sdut Object-Oriented Programming Practice 10 (Operator overloading)