作用:实现两个自定义数据类型的相加运算

    示例:

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

    网址:https://www.bilibili.com/video/BV1et411b73Z?p=121