C++第8课--函数重载分析(上)

本文通过三个实验深入探讨了C++中函数重载的使用、冲突情况及其实质,展示了如何通过函数签名来区分不同的函数实现。

本文学习自 狄泰软件学院 唐佐林老师的 C++课程


实验1:函数重载使用
实验2:函数默认参数 VS 函数重载 ------> 产生冲突
实验3:函数重载的本质


在这里插入图片描述

实验1:函数重载使用

#include <stdio.h>
#include <string.h>

int func(int x)
{
    return x;
}

int func(int a, int b)
{
    return a + b;
}

int func(const char* s)
{
    return strlen(s);
}


int main(int argc, char *argv[])
{
    printf("%d\n", func(3));
    printf("%d\n", func(4, 5));
    printf("%d\n", func("D.T.Software"));
    
    return 0;
}

mhr@ubuntu:~/work/c++$ g++ 8-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out 
3
9
12
mhr@ubuntu:~/work/c++$ 

在这里插入图片描述

在这里插入图片描述

实验2:函数默认参数 VS 函数重载 ------> 产生冲突

#include <stdio.h>

int func(int a, int b, int c = 0)
{
    return a * b * c;
}

int func(int a, int b)
{
    return a + b;
}


int main(int argc, char *argv[])
{
    int c = func(1, 2);
    
    return 0;
}

mhr@ubuntu:~/work/c++$ g++ 8-2.cpp
8-2.cpp: In function ‘int main(int, char**)’:
8-2.cpp:16:22: error: call of overloaded ‘func(int, int)’ is ambiguous
     int c = func(1, 2);
                      ^
8-2.cpp:3:5: note: candidate: int func(int, int, int)
 int func(int a, int b, int c = 0)
     ^
8-2.cpp:8:5: note: candidate: int func(int, int)
 int func(int a, int b)
     ^
mhr@ubuntu:~/work/c++$ 

在这里插入图片描述
报错,产生冲突。

在这里插入图片描述

在这里插入图片描述

实验3:函数重载的本质

#include <stdio.h>

int add(int a, int b)  // int(int, int)
{
    return a + b;
}

int add(int a, int b, int c) // int(int, int, int)
{
    return a + b + c;
}

int main()
{
    printf("%p\n", (int(*)(int, int))add);
    printf("%p\n", (int(*)(int, int, int))add);

    return 0;
}

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ma浩然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值