加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

类中的函数重载

发布时间:2020-12-16 09:14:57 所属栏目:百科 来源:网络整理
导读:目录 1. 函数重载回顾 2. 类中的函数重载 1. 函数重载回顾 函数重载的 本质为相互独立的不同函数 C++通过 函数名 和 函数参数 确定函数调用 无法 直接通过 函数名 得到重载函数的 入口地址 函数重载 必然发生在同一个作用域中 2. 类中的函数重载 类的成员函

目录

  • 1. 函数重载回顾
  • 2. 类中的函数重载

1. 函数重载回顾

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

2. 类中的函数重载

类的成员函数可以进行重载,包括

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

注意:函数重载必然发生在同一个作用域中,因此全局函数和类的成员函数无法构成重载。

#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 = %dn",i);
    }

    int getI()
    {
        return i;
    }
};

void func()
{
    printf("void func()n");
}

void func(int i)
{
    printf("void func(int i),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;
}

重载的意义

  • 通过函数名对函数功能进行提示
  • 通过参数列表对函数用法进行提示
  • 扩展系统中已经存在的函数功能
#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 = "D.T.Software";
    char buf[8] = {0};

    strcpy(buf,s,sizeof(buf) - 1);

    printf("%sn",buf);

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读