C++之函数重载

重载函数

(1)定义:将一组功能非常相近的函数定义为重载函数。

(2)一组重载函数是以参数类型或参数个数加以区别的,只有返回值不同不是一组重载函数,将会产生编译错误。

(3)编译器调用重载函数的规

#include <stdio.h>

void ShowMessage(const char* Text,int Type);
void ShowMessage(const char* Text,unsigned int Type);

int main()
{
unsigned char i=0;
ShowMessage("hello",i);
return 0;
}

void ShowMessage(const char* Text,int Type)
{
printf("Text=%s,Type=%d\n",Text,Type+1);
}
void ShowMessage(const char* Text,unsigned int Type)
{
printf("Text=%s,Type=%d\n",Text,Type);
}

输出结果:Text=hello,Type=1

因为对参数个数相同的重载进行调用时,编译器依次使用下面的规则将实参与形参进行匹配,确实重载函数的调用。

(1)具有与实参类型相同的形参的重载函数

(2)转换实参,将T转换成T&,或T&转换为T,或T转换为const T,然后寻找形参类型匹配的重载函数(T为某数据类型)

(3)实参进行标准的类型转换,如char→int→unsigned int,然后寻找形参类型匹配的重载函数

(4)使用构造函数的转换实参,使其与某一重载函数匹配。例如,如果类A有构造函数A(int),那么int型转换函数进行转换,使其一重载函数匹配

(5)使用类型转换函数进行转换,使其与某一重载函数匹配

显然,上述例子符合第3种情况。

再看下面例子:

#include <stdio.h>

void ShowMessage(const char* Text,const char* Caption);
void ShowMessage(const char* Text,unsigned int Type);

int main()
{
ShowMessage("hello",NULL); //NULL==0
return 0;
}

void ShowMessage(const char* Text,const char* Caption)
{
printf("Text=%s,Type=%s\n",Text,Caption);
}
void ShowMessage(const char* Text,unsigned int Type)
{
printf("Text=%s,Type=%d\n",Text,Type);
}

结果:会产生编译错误 error C2668: 'ShowMessage' : ambiguous call to overloaded function

因为编译器无法判断第二个参数是空字符串NULL,还是整数0。所以,重载函数的定义和调用会涉及类型转换的细节问题,在设计时要考虑全面。

原文地址:https://www.cnblogs.com/danshui/p/2345045.html