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 two computing volumes involved in the operation can be class objects 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
#include <iostream>#include <string>#include <algorithm>using namespace std;class Complex{ private: int real, imag; public: Complex() { real=0; imag=0; } Complex(double r, double i) { real=r; imag=i; } friend Complex operator +(Complex &c1, Complex &c2 ) { return Complex(c1.real+c2.real, c1.imag+c2.imag ); } friend Complex operator +(int &i, Complex &c2) { return Complex(i+c2.real, c2.imag ); } friend Complex operator +(Complex &c1, int &i ) { return Complex(i+c1.real, c1.imag ); } void sett(); void disp();}c1,c2;void Complex::sett(){ cin>>real>>imag;}void Complex::disp(){ if(imag<0) { cout<<real<<imag<<‘i‘<<endl; } else cout<<real<<‘+‘<<imag<<‘i‘<<endl;}int main(){ int ii; Complex a, b, c; c1.sett(); c2.sett(); cin>>ii; a=c1+c2; a.disp(); b=c1+ii; b.disp(); c=ii+c1; c.disp(); return 0;}
Object-Oriented Programming Practice 10 (Operator overloading)