定义复数类的加法与减法(运算符+-重载).cpp 942 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #include <iostream>
  2. class Complex {
  3. private:
  4. double real;
  5. double imag;
  6. public:
  7. Complex(double r = 0, double i = 0) : real(r), imag(i) {}
  8. // 重载加法运算符
  9. Complex operator+(const Complex& c) {
  10. return Complex(real + c.real, imag + c.imag);
  11. }
  12. // 重载减法运算符
  13. Complex operator-(const Complex& c) {
  14. return Complex(real - c.real, imag - c.imag);
  15. }
  16. friend std::ostream& operator<<(std::ostream& out, const Complex& c) {
  17. out << c.real;
  18. if (c.imag >= 0) {
  19. out << "+i" << c.imag;
  20. } else {
  21. out << "-i" << -c.imag;
  22. }
  23. return out;
  24. }
  25. };
  26. int main() {
  27. Complex a(2, 5), b(7, 8), c(0, 0);
  28. // c=a+b
  29. c = a + b;
  30. std::cout << c << std::endl;
  31. // c=4.1+a
  32. c = Complex(4.1, 0) + a;
  33. std::cout << c << std::endl;
  34. // c=b-5.6
  35. c = b - Complex(5.6, 0);
  36. std::cout << c << std::endl;
  37. return 0;
  38. }