#include class Complex { private: double real; double imag; public: Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 重载加法运算符 Complex operator+(const Complex& c) { return Complex(real + c.real, imag + c.imag); } // 重载减法运算符 Complex operator-(const Complex& c) { return Complex(real - c.real, imag - c.imag); } friend std::ostream& operator<<(std::ostream& out, const Complex& c) { out << c.real; if (c.imag >= 0) { out << "+i" << c.imag; } else { out << "-i" << -c.imag; } return out; } }; int main() { Complex a(2, 5), b(7, 8), c(0, 0); // c=a+b c = a + b; std::cout << c << std::endl; // c=4.1+a c = Complex(4.1, 0) + a; std::cout << c << std::endl; // c=b-5.6 c = b - Complex(5.6, 0); std::cout << c << std::endl; return 0; }