使用函数指针解决函数重载二义性调用问题

当实参对应重载函数的多个可行函数,且每个可行函数各自在一个实参上实现了更好的匹配时,编译器会因为程序具有二义性而报错。

例如:

#include<iostream>
using std::string;
using std::cout;
using std::cin;
using std::endl;

void ff(int, int)
{//重载函数1
	cout << "f1" << endl;
}
void ff(double, double = 3.14)
{//重载函数2
	cout << "f2" << endl;
}

int main()
{
	ff(2, 3.4);//第一个实参更加匹配函数1,第二个实参更加匹配函数2
	return 0;
}

此时编译器会报告有多个重载函数“ff”的实例与参数列表匹配。

可知这种函数重载方式本身不是特别合理。

但是如果我们非要使用这种具有二义性的实参该怎么办呢?

可以通过函数指针来指向想要调用的函数,能够避免二义性的产生。

#include<iostream>
using std::string;
using std::cout;
using std::cin;
using std::endl;
void ff(int, int)
{
	cout << "f1" << endl;
}
void ff(double, double = 3.14)
{
	cout << "f2" << endl;
}

int main()
{
	void (*pf)(double ,double);//函数指针pf指向第二个重载函数
	pf = ff;
	pf(2, 3.4);                //将调用第二个重载函数
	return 0;
}

虽然可以通过函数指针来避免这个问题,但是防止此类问题出现的最好方法还在于对重载函数形参的良好设计上。

原文地址:https://www.cnblogs.com/sgawscd/p/12228872.html