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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include <iostream>
  2. using namespace std;
  3. class Complex {
  4. private:
  5. double real;
  6. double imag;
  7. public:
  8. Complex(double r = 0, double i = 0) : real(r), imag(i) {}
  9. Complex operator+(const Complex& other) const {
  10. return Complex(real + other.real, imag + other.imag);
  11. }
  12. Complex operator-(const Complex& other) const {
  13. return Complex(real - other.real, imag - other.imag);
  14. }
  15. friend ostream& operator<<(ostream& os, const Complex& num) {
  16. os << num.real << "+i" << num.imag;
  17. return os;
  18. }
  19. Complex operator+(double value) const {
  20. return Complex(real + value, imag);
  21. }
  22. Complex operator-(double value) const {
  23. return Complex(real - value, imag);
  24. }
  25. friend Complex operator+(double value, const Complex& num);
  26. friend Complex operator-(double value, const Complex& num);
  27. };
  28. Complex operator+(double value, const Complex& num) {
  29. return Complex(value + num.real, num.imag);
  30. }
  31. Complex operator-(double value, const Complex& num) {
  32. return Complex(value - num.real, -num.imag);
  33. }
  34. int main() {
  35. Complex a(2, 5), b(7, 8), c(0, 0);
  36. c = a + b;
  37. cout << c << endl;
  38. c = 4.1 + a;
  39. cout << c << endl;
  40. c = b - 5.6;
  41. cout << c << endl;
  42. return 0;
  43. }