20 类中的函数重载

1 函数重载回顾

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

2 类中的重载

  • 类中的成员函数可以进行重载

    • 构造函数的重载
    • 普通成员函数的重载
    • 静态成员函数的重载
  • 问题:全局函数,普通成员函数以及静态成员函数之间是否可以构成重载?

    • 不构成重载:不在同一个作用域
  • 示例:类与重载

    • Demo

      #include <stdio.h>
      
      class Test
      {
          int i;
      public:
          Test()
          {
              printf("Test::Test()
      ");
              this->i = 0;
          }
          
          Test(int i)
          {
              printf("Test::Test(int i)
      ");
              this->i = i;
          }
          
          Test(const Test& obj)
          {
              printf("Test(const Test& obj)
      ");
              this->i = obj.i;
          }
          
          static void func()
          {
              printf("void Test::func()
      ");
          }
          
          void func(int i)
          {
              printf("void Test::func(int i), i = %d
      ", i);
          }
          
          int getI()
          {
              return i;
          }
      };
      
      void func()
      {
          printf("void func()
      ");
      }
      
      void func(int i)
      {
          printf("void func(int i), i = %d
      ", i);
      }
      
      int main()
      {
          func();        //void func()
          func(1);       //void func(int i), i = 1
          
          Test t;        // Test::Test()
          Test t1(1);    // Test::Test(int i)
          Test t2(t1);   // Test(const Test& obj)
          
          func();        // void func()
          Test::func();  // void Test::func()
          
          func(2);       // void func(int i), i = 2;
          t1.func(2);    // void Test::func(int i), i = 2
          t1.func();     // void Test::func()
          
          return 0;
      }
      
  • 重载的意义

    • 通过函数名对函数功能进行提示
    • 通过参数列表对函数用法进行提示
    • 扩展系统中已经存在的函数功能
  • 示例:重载的意义

    • Demo

      #include <stdio.h>
      #include <string.h>
      
      int main()
      {
          const char* s = "ABCD";
          char buf[8] = {0};
          
          strcpy(buf, s);
          
          printf("%s
      ", buf);
          
          return 0;
      }
      
    • 编译运行

      • 可能存在的问题:当 buf 的大小不够时,会发生内存越界
      ABCD
      
    • 改进:利用 strncpy 函数扩展 strcpy 函数,方便使用

      #include <stdio.h>
      #include <string.h>
      
      char* strcpy(char* buf, const char* str, unsigned int n)
      {
          return strncpy(buf, str, n);
      }
      
      int main()
      {
          const char* s = "ABCD";
          char buf[8] = {0};
          
          //strncpy(buf, s,sizeof(buf)-1);
          strcpy(buf, s, sizeof(buf)-1);
          
          printf("%s
      ", buf);
          
          return 0;
      }
      
    • 编译运行

      ABCD
      
原文地址:https://www.cnblogs.com/bky-hbq/p/13723563.html