1.函数重载回顾

—-函数重载的本质为相互独立不同的函数
—-c++中通过函数名和函数参数确定函数调用
—-无法直接通过函数名得到重载函数的入口地址
—-函数重载必然发生在同一个作用域中


2.类中的重载

类中的成员函数可以进行重载
—-构造函数的重载
—-普通成员函数的重载
—-静态成员函数的重载
问题:全局函数,普通成员函数以及静态成员函数之间是否可以构成重载?
1.重载函数的本质为多个不同的函数
2.函数名和参数列表是唯一的标识
3.重载函数必须发生在同一个作用域中

  1. #include <stdio.h>
  2. void func()
  3. {
  4. printf("void func()\n");
  5. }
  6. void func(int i)
  7. {
  8. printf("void func(int i)\n");
  9. }
  10. class Test
  11. {
  12. int i;
  13. public:
  14. Test()
  15. {
  16. printf("Test::Test()\n");
  17. this->i = 0;
  18. }
  19. Test(int i)
  20. {
  21. printf("Test::Test(int i)\n");
  22. this->i = i;
  23. }
  24. Test(const Test& obj)
  25. {
  26. printf("Test(const Test& obj)\n");
  27. this->i = obj.i;
  28. }
  29. static void func()
  30. {
  31. printf("void Test::func()\n");
  32. }
  33. void func(int i)
  34. {
  35. printf("void Test::func(int i), i = %d\n", i);
  36. }
  37. int getI()
  38. {
  39. return i;
  40. }
  41. };
  42. void func()
  43. {
  44. printf("void func()\n");
  45. }
  46. void func(int i)
  47. {
  48. printf("void func(int i), i = %d\n", i);
  49. }
  50. int main()
  51. {
  52. func();
  53. func(1);
  54. Test t; // Test::Test()
  55. Test t1(1); // Test::Test(int i)
  56. Test t2(t1); // Test(const Test& obj)
  57. func(); // void func()
  58. Test::func(); // void Test::func()
  59. func(2); // void func(int i), i = 2;
  60. t1.func(2); // void Test::func(int i), i = 2
  61. t1.func(); // void Test::func()
  62. return 0;
  63. }

3.深度的意义

重载的意义
—-通过函数名对函数功能进行提示
—-通过参数列表对函数用法进行提示
—-拓展系统中已经存在的函数功能
(代码的自注释)

例子:通过函数重载扩展了原有的函数库

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

问题:重载能够扩展系统中已经存在的函数功能!
那么重载是否也能够扩展其他更多的功能?操作符重载

思考:
下面的复数解决方案是否可行?
class Complex
{
public:
int a;
int b;
}
int main()
{
Complex c1 = {1,2};
Complex c2 = {3,4};
Complex c3 = c1 + c2;

return 0;
}

小结:
1.类的成员函数之间可以进行重载
2.重载必须发生在同一个作用域中
3.全局函数和成员函数不能构成重载关系
4.重载的意义在于扩展已经存在的功能