函数重载导致的二义性

函数重载主要是一个匹配问题,分为精准匹配,提升匹配和类型转换匹配三种:


精准匹配

#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的重载函数这时候就产生匹配冲突也就是出现了多个匹配,这样的情况就会就导致二义性;

所以在使用函数重载时推荐使用精准匹配进行函数重载,以便避免出现二义性!避免使用如int*和char*这样的难以辨识的参数作为重载区分

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值