定义一个复数类Complex,重载运算符“+”、“-”、“*”、“~”“==”以及“<<”,使之能用于复数的加、减、乘、求反(虚部反)、比较和输出等运算。其中“+”“-”“~”重载为成员函数,“*”“==”“<<”重载为友元函数。
#includeusing namespace std; class Complex { private: double real; double imag; public: Complex() { real = 0; imag = 0; }; Complex(double r, double i) :real(r), imag(i) {}; void display(); Complex operator+(Complex c1); Complex operator-(Complex c1); Complex operator~(); friend Complex operator* (Complex c1, Complex c2); friend ostream& operator <<(ostream& out, Complex& c); friend bool operator==(Complex&, Complex&); }; void Complex::display() { cout << "(" << real << "," << imag << "i)" << endl; } Complex Complex::operator+(Complex c1) { Complex c; c.real = real + c1.real; c.imag = imag + c1.imag; return c; } Complex Complex::operator-(Complex c1) { Complex c; c.real = real - c1.real; c.imag = imag - c1.imag; return c; } Complex Complex:: operator~() { this->imag = 0 - this->imag; return *this; } Complex operator* (Complex c1, Complex c2) { return Complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag + c2.real); } ostream& operator <<(ostream& out, Complex& c) { out << "(" << c.real << "," << c.imag << "i)" ; return out; } bool operator==(Complex& c1, Complex& c2) { if (c1.real == c2.real && c1.imag == c2.imag) return true; else return false; } int main() { Complex c1(1, 2), c2(3, 4); cout << c1 << endl; cout << c2 << endl; (c1 + c2).display(); (c2 - c1).display(); (c1 * c2).display(); (~c1).display(); cout << (c1 == c2) << endl; }



