您的位置:首页 > 编程语言 > C语言/C++

C++中函数指针遇上函数重载

2018-03-05 00:38 176 查看

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<>来区分重载函数的版本。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: