4-1 operator overloading of complex classes Time Limit: 1000 ms memory limit: 65536 K 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 Source
# Include <iostream> using namespace STD; Class complex // defines the complex class {PRIVATE: Double real; double imag; public: complex () // The default value is 0 {real = 0; imag = 0;} complex (double A, double B) // value assignment function {real = A; imag = B;} complex operator + (complex & C ); // declare the overload operator "+" complex operator-(complex & C); // declare the overload operator "-" Friend ostream & operator <(ostream &, complex &); // declare the operator "<" to overload as a friend function}; complex: Operator + (complex & C) // define the overload operator "+" function {complex D; D. real = real + C. real; D. imag = imag + C. imag; return D;} complex: Operator-(complex & C) // defines the function {complex D; D. real = real-c.real; D. imag = imag-c.imag; return D;} ostream & operator <(ostream & output, complex & C) // defines the operator '<' overload function {output <C. real; If (C. imag> = 0) Output <"+"; Output <C. imag <"I"; return output;} int main () {complex A (3.2, 4.5), B (8.9, 5.6 ); cout <"A =" <A <Endl; cout <"B =" <B <Endl; Complex C; C = A + B; // operator + used for complex operations cout <"A + B =" <C <Endl; C = A-B; // operator-used for complex operations cout <"a-B =" <C <Endl; return 0 ;}
Operator Overloading of sdut 4-1 complex classes