1、加号运算符重载.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. //4.5 运算符重载
  2. //运算符重载概念:对已有的运算符进行重新定义,赋予其另一种功能,以适应不同的数据类型
  3. //4.5.1
  4. //作用:实现两个自定义数据类型相加的运算
  5. #if(0)
  6. #include <iostream>
  7. //➕号运算符重载
  8. //1、成员函数重载?
  9. //2、全局函数重载?
  10. class Person
  11. {
  12. public:
  13. //1、通过成员函数重载+
  14. //Person operator+(Person& p)
  15. //{
  16. // Person temp;
  17. // temp.m_A = this->m_A + p.m_A;
  18. // temp.m_B = this->m_B + p.m_B;
  19. // return temp;
  20. //}
  21. int m_A;
  22. int m_B;
  23. };
  24. //2、通过全局函数重载+号
  25. Person operator+(Person& p1, Person& p2)
  26. {
  27. Person temp;
  28. temp.m_A = p1.m_A + p2.m_A;
  29. temp.m_B = p2.m_B + p2.m_B;
  30. return temp;
  31. }
  32. //函数重载的版本
  33. Person operator+(Person& p1, int num)
  34. {
  35. Person temp;
  36. temp.m_A = p1.m_A + num;
  37. temp.m_B = p1.m_B + num;
  38. return temp;
  39. }
  40. void test01()
  41. {
  42. Person p1;
  43. p1.m_A = 10;
  44. p1.m_B = 10;
  45. Person p2;
  46. p2.m_A = 10;
  47. p2.m_B = 10;
  48. //成员函数重载本质的调用
  49. //Person p3 = p1.operator+(p2);
  50. //全局函数重载本质的调用
  51. //Person p3 = operator+(p1, p2);
  52. Person p3 = p1 + p2;
  53. //运算符重载也可以发生函数重载
  54. Person p4 = p1 + 100; //Person + int
  55. std::cout << "p3.m_A = " << p3.m_A << std::endl;
  56. std::cout << "p3.m_B = " << p3.m_B << std::endl;
  57. std::cout << "p4.m_A = " << p4.m_A << std::endl;
  58. std::cout << "p4.m_B = " << p4.m_B << std::endl;
  59. }
  60. int main()
  61. {
  62. test01();
  63. system("pause");
  64. return 0;
  65. }
  66. //总结1 :对于内置的数据类型的表达式的运算符是不可能改变的
  67. //总结2 :不要滥用运算符重载
  68. #endif