C++深入分析回顾函数重载

2022-11-13 09:11:13 函数 重载 回顾

一、函数重载回顾

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

二、类中的重载

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

  • 构造函数的重载
  • 普通成员函数的重载
  • 静态成员函数的重载

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

注意事项

  • 重载函数的本质为多个不同的函数
  • 函数名和参数列表是唯一的标识
  • 函数重载必须发生在同一个作用域中

所以类的成员函数和全局函数不能构成重载,因为全局函数位于全局的命名空间当中,而成员函数位于类里面,作用域不一样。

下面看一个重载的示例:

#include <stdio.h>
class Test
{
    int i;
public:
    Test()
    {
        printf("Test::Test()\n");
        this->i = 0;
    }
    Test(int i)
    {
        printf("Test::Test(int i)\n");
        this->i = i;
    }
    Test(const Test& obj)
    {
        printf("Test(const Test& obj)\n");
        this->i = obj.i;
    }
    static void func()
    {
        printf("void Test::func()\n");
    }
    void func(int i)
    {
        printf("void Test::func(int i), i = %d\n", i);
    }
    int getI()
    {
        return i;
    }
};
void func()
{
    printf("void func()\n");
}
void func(int i)
{
    printf("void func(int i), i = %d\n", i);
}
int main()
{
    func();
    func(1);
    Test t;        // 初始化,调用没有参数的构造函数Test(),输出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;
}

输出结果如下:

这个例子展示了类中函数的重载以及全局函数的重载,值得多阅读几遍!!

三、重载的意义

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

下面看一个字符串拷贝函数的重载:

#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 = "AutumnZe";
    char buf[8] = {0};
    //strcpy(buf, s);
    strcpy(buf, s, sizeof(buf)-1);
    printf("%s\n", buf);
    return 0;
}

输出结果如下:

四、小结

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

到此这篇关于C++深入分析回顾函数重载的文章就介绍到这了,更多相关C++函数重载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章