重载
1.同一个标示符在不同的上下文有不同的意义。
比如:洗衣服和洗脸是不同的,或者有不同的含义。
函数重载
1.用同一个函数名定义不同的函数
2.当函数名和不同的参数搭配时函数的含义是不同的
例子:
#include <iostream>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int func(int x) //一个int参数
{
return x;
}
int func(int a, int b)//两个int参数
{
return a + b;
}
int func(const char* s)//一个char*参数
{
return strlen(s); //返回字符串的长度
}
int main(int argc, char** argv) {
int c = 0;
c = func(1); //调用第一个函数,因为这个函数的参数类型和个数都对应
printf("c = %d\n", c);
c = func(1, 2);//调用第二个函数,参数类型和个数都对应
printf("c = %d\n", c);
c = func("lp"); //调用第三个函数,参数类型和个数都符合
printf("c = %d\n", c);
return 0;
}
C++中的函数重载至少满足一下一个条件
1.参数个数不同
2.参数类型不同
3.参数顺序不同
上面和下面的例子可以说明这个问题。
#include <iostream>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int func(int a, const char* s) //一个int参数 ,一个char*指针,参数顺序不同
{
return a;
}
int func(const char* s, int a)//一个char*指针,一个int参数 ,参数顺序不同
{
return strlen(s);
}
int main(int argc, char** argv) {
int c = 0;
c = func(1, "lp"); //调用第一个函数,因为这个函数的参数类型和个数都对应
printf("c = %d\n", c);
c = func("lll", 2);//调用第二个函数,参数类型和个数都对应
printf("c = %d\n", c);
return 0;
}
当函数的默认参数遇上函数重载会发生什么事情,就很有可能出现程序的二义性,所以在做产品的时候用的C++语言,
用了默认参数就不要用函数重载,用来函数重载就不要用默认参数。
看一下例子
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int func(int a, int b, int c = 1)
{
return a + b + c;
}
int func(int a, int b)
{
return a + b;
}
int main(int argc, char** argv) {
int c = 0;
c = func(1, 2); //存在二义性,调用失败。
printf("c = %d\n", c);
return 0;
}
//上述程序会出错,不能进行编译,有错误,无法确定调用哪一个函数。
编译器调用重载函数的准则
1.将所有同名的函数作为候选择
2.尝试寻找可行的候选参数
精确匹配实参
通过默认参数能够匹配实参
通过默认的类型转换匹配实参
3.匹配失败
最终寻找到的可行的候选函数不唯一,就出现二义性,程序出错,编译失败。
无法匹配所有候选者,函数未定义,编译失败。
函数重载的注意事项
1.重载函数在本质上是相互独立的不同的函数
2.重载函数的函数类型是不同的
3.函数返回值不能作为函数重载的依据
函数重载与函数指针
当使用重载函数名对函数指针进行幅值时
根据重载规则挑选与函数指针参数列表一致的候选者
严格匹配候选者的函数类型与函数指针的函数类型
例子如下:
#include <iostream>
#include <string.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int func(int a)
{
return a;
}
int func(int a, int b)
{
return a + b;
}
int func(const char* s)
{
return strlen(s);
}
typedef int(*PFUNC)(int a);
int main(int argc, char** argv) {
int c = 0;
PFUNC p = func;
c = p(1);
printf("c = %d\n", c);
return 0;
}