函数重载主要是一个匹配问题,分为精准匹配,提升匹配和类型转换匹配三种:
精准匹配
#include<iostream>
#include "string.h"
using namespace std;
void MyCout(long n)
{
cout << "参数为长整形!" << endl;
}
void MyCout(int n)
{
cout << "参数为整形!" << endl;
}
int main()
{
long a = 100;
int b = 200;
MyCout(a);
MyCout(b);
system("pause");
return 0;
}
想这样调用重载函数时传入的参数存在与它完全匹配的重载函数的情况称为精准匹配!
提升匹配
#include<iostream>
#include "string.h"
using namespace std;
void MyCout(long n)
{
cout << "参数为长整形!" << endl;
}
void MyCout(int n)
{
cout << "参数为整形!" << endl;
}
int main()
{
short a = 100;//参数为short,不存在完全匹配的函数
MyCout(a);
system("pause");
return 0;
}
向这样调用重载函数时的参数并不存在能与其完全匹配的重载函数,在参数提升为其它类型后存在唯一与其完全匹配的重载函数的情况称为提升匹配。
这种提升是编译器的一个特性,比如bool 到 int、char到int、short 到int,float到double (也叫隐式转换)
类型转换匹配
类型转换匹配也叫标准转换匹配常见的有int 到double、double到int、double到long double、int到unsigned int;
#include<iostream>
using namespace std;
void MyCout(int n)
{
cout << "参数为整形!" << endl;
}
void MyCout(char* n)
{
cout << "参数为字符指针!" << endl;
}
int main()
{
double a=100;
MyCout(a);
system("pause");
return 0;
}
从上图可以看出
虽然调用函数时传入的参数是double并不存在完全匹配的重载函数,但是经过类型转换后成功匹配到了参数类型为int的重载函数。
多个匹配导致的二义性
#include<iostream>
#include "string.h"
using namespace std;
void MyCout(double n)
{
cout << "参数为整形!" << endl;
}
void MyCout(char n)
{
cout << "参数为字符指针!" << endl;
}
void MyCout(unsigned int n)
{
cout << "参数为double!" << endl;
}
int main()
{
int a=100;
MyCout(a);
system("pause");
return 0;
}
如上图所示:
这种情况下int类型通过转换后均可以匹配参数分别为unsigned int
,double和char的重载函数这时候就产生匹配冲突也就是出现了多个匹配,这样的情况就会就导致二义性;