5 类中的函数重载

image.png

(1)函数重载本质
a.重载函数本质为相互独立的不同函数
b.c++中,函数名和参数列表是唯一标示
c.函数重载必须发生在同一作用域

(2)重载的意义
a.通过函数名对函数宫内进行提示
b.通过参数列表对函数用法进行提示
c.扩展系统中已经存在的函数功能

  1. #include <stdio.h>
  2. #include <string.h>
  3. char* strcpy(char* buf, const char* str, unsigned int n)
  4. {
  5. return strncpy(buf, str, n);
  6. }
  7. int main()
  8. {
  9. const char* s = "D.T.Software";
  10. char buf[8] = {0};
  11. //strcpy(buf, s);
  12. strcpy(buf, s, sizeof(buf)-1);
  13. printf("%s\n", buf);
  14. return 0;
  15. }

(3)类中的重载
构造函数的重载
普通成员函数的重载
静态成员函数的重载
全局函数,普通函数以及静态成员之间是否可以构成重载?
函数实现下:

  1. #include <stdio.h>
  2. class Test
  3. {
  4. int i;
  5. public:
  6. Test()
  7. {
  8. printf("Test::Test()\n");
  9. this->i = 0;
  10. }
  11. Test(int i)
  12. {
  13. printf("Test::Test(int i)\n");
  14. this->i = i;
  15. }
  16. Test(const Test& obj)
  17. {
  18. printf("Test(const Test& obj)\n");
  19. this->i = obj.i;
  20. }
  21. static void func()
  22. {
  23. printf("void Test::func()\n");
  24. }
  25. void func(int i)
  26. {
  27. printf("void Test::func(int i), i = %d\n", i);
  28. }
  29. int getI()
  30. {
  31. return i;
  32. }
  33. };
  34. void func()
  35. {
  36. printf("void func()\n");
  37. }
  38. void func(int i)
  39. {
  40. printf("void func(int i), i = %d\n", i);
  41. }
  42. int main()
  43. {
  44. func();
  45. func(1);//通过这两个函数可知全局函数可以重载
  46. Test t; // Test::Test()
  47. Test t1(1); // Test::Test(int i)
  48. Test t2(t1); // Test(const Test& obj) 构造函数间可以重载
  49. func(); // void func()
  50. Test::func(); // void Test::func()类的静态成员函数与全局函数可重载
  51. func(2); // void func(int i), i = 2;
  52. t1.func(2); // void Test::func(int i), i = 2
  53. t1.func(); // void Test::func() 类的静态成员函数与普通函数也可以重载
  54. return 0;
  55. }

**

(4)小结
a.类的成员函数之间可以进行重载
b.重载必需发生在同一个作用域
c.全局函数和成员函数不能构成重载关系
d.重载的意义在于扩展已经存在的功能