C++重载的概念

重载
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;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值