运算符重载的需求

1.PNG
2.PNG

运算符重载的概念

3.PNG

运算符重载的形式

4.PNG

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Complex
  4. {
  5. public:
  6. double real, imag;
  7. Complex(double, double);
  8. Complex operator-(const Complex &);//重载为成员函数时,参数个数=运算符目数-1
  9. };
  10. Complex::Complex(double r, double i)
  11. {
  12. real = r;
  13. imag = i;
  14. }
  15. Complex operator+(const Complex &c1, const Complex &c2)
  16. {
  17. return Complex(c1.real + c2.real, c1.imag + c2.imag);//返回临时对象
  18. }//重载为外部普通函数时,参数个数=运算符目数
  19. Complex Complex::operator-(const Complex &c)
  20. {
  21. return Complex(real - c.real, imag - c.imag);
  22. }
  23. int main(void)
  24. {
  25. Complex c1(4, 4), c2(1, 1);
  26. Complex c3 = c1 + c2;//等价于c3=operator+(c1,c2)
  27. Complex c4 = c1 - c2;//等价于c4=c1.operator-(c2)
  28. cout << c3.real << ends << c3.imag << endl;// 5 5
  29. cout << c4.real << ends << c4.imag << endl;// 3 3
  30. return 0;
  31. }