本文学习自 狄泰软件学院 唐佐林老师的 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;
}
来源:CSDN
作者:奶牛养殖场小马
链接:https://blog.csdn.net/LinuxArmbiggod/article/details/104088978