第二十九课:类中的函数重载----狄泰软件学院

文章内容来源于狄泰软件学院唐老师课件。
一、函数重载回顾

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

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

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

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

  1. 重载函数的本质为多个不同的函数
  2. 函数名和参数列表是唯一的标识
  3. 函数重载必须发生在同一个作用域中(全局函数不能同其他域中的函数进行重载)

实例分析:类与重载全面分析

#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()//与类中的void func()函数不构成重载
{
    printf("void func()\n");
}

void func(int i)//与类中的void func()函数不构成重载
{
    printf("void func(int i), i = %d\n", i);
}

int main()
{
    func();
    func(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;
}
void func()
void func(int i), i = 1
Test::Test()
Test::Test(int i)
Test(const Test& obj)
void func()
void Test::func()
void func(int i), i = 2
void Test::func(int i), i = 2
void Test::func()

深度意义:
重载的意义:

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

实例:重载的意义分析

#include <stdio.h>
#include <string.h>
//通过函数重载扩展了C语言中strcpy函数。扩展了功能
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);
    strcpy(buf, s, sizeof(buf)-1);
    
    printf("%s\n", buf);
    
    return 0;
}

思考:重载能够扩展系统已经存在的函数功能,那么重载是否能够扩展其他更多的功能?
下面的复数解决方案是否可行?

在这里插入图片描述
总结:

  1. 类的成员函数之间可以重载
  2. 重载必须发生在同一个作用域中
  3. 全局函数和成员函数不能构成重载关系
  4. 重载的意义在于扩展已经存在的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值