1. //加号运算符重载
    2. class Person
    3. {
    4. public:
    5. //1 成员函数重载+号
    6. Person operator+(Person& p)
    7. {
    8. Person temp;
    9. temp.m_A = this->m_A + p.m_A;
    10. temp.m_B = this->m_B + p.m_B;
    11. return temp;
    12. }
    13. int m_A;
    14. int m_B;
    15. };
    16. //2 全局函数重载+号
    17. //Person operator+(Person& p1, Person& p2)
    18. //{
    19. // Person temp;
    20. // temp.m_A = p1.m_A + p2.m_A;
    21. // temp.m_B = p1.m_B + p2.m_B;
    22. // return temp;
    23. //}
    24. //运算符重载也可以发生函数重载
    25. Person operator+(Person& p1, int num)
    26. {
    27. Person tmp;
    28. tmp.m_A = p1.m_A + num;
    29. tmp.m_B = p1.m_B + num;
    30. return tmp;
    31. }
    32. void test01()
    33. {
    34. Person p1;
    35. p1.m_A = 10;
    36. p1.m_B = 10;
    37. Person p2;
    38. p2.m_A = 10;
    39. p2.m_B = 10;
    40. //成员函数重载本质调用
    41. //Person p3 = p1.operator+(p2);
    42. //全局函数重载本质调用
    43. //Person p3 = operator+(p1, p2);
    44. //函数重载简化写法
    45. Person p3 = p1 + p2;
    46. cout << "p3 m_A = " << p3.m_A << endl;
    47. cout << "p3 m_B = " << p3.m_B << endl;
    48. //运算符重载也可以发生函数重载
    49. Person p4 = p1 + 100;
    50. cout << "p4 m_A = " << p4.m_A << endl;
    51. cout << "p4 m_B = " << p4.m_B << endl;
    52. }
    53. int main()
    54. {
    55. test01();
    56. system("pause");
    57. return 0;
    58. }