C++中函数指针遇上函数重载
1、C++编译器会按照函数指针的类型自动选择重载函数
test.cpp
#include <iostream>
using namespace std;
void print(int a)
{
cout << "a is " << a << endl;
}
void print()
{
cout << "hello world" << endl;
}
typedef void (* Fun)(int);
typedef void (* Fun2)();
int main()
{
Fun pPrint = print;
Fun2 pPrint2 = print;
pPrint(12);
pPrint2();
return 0;
}
运行结果为:
a is 12
hello world
2、重载函数作为参数传递时,特别形参的类型不是确定的函数指针类型时,如void *,例如Qt中的QObject::connect()函数,重载的信号或槽传入到connect时,可以使用static_cast<>来区别重载函数:
connect(subWidget, static_cast<void(SubWidget::*)()>(&SubWidget::switchWin), this, &MainWidget::switchWinSlot);
connect()函数的第2个和第4个形参都是const char *类型,不是指定好的函数指针类型,所以我们可以通过static<>来区分重载函数的版本。