一.函数指针
定义、使用方法如下:
#include <iostream>
using namespace std;
//函数指针
int func1(int a, int b) {
return a * b;
}
//1.定义一种函数类型
typedef int(my_func) (int, int);
//2.定义一种指向这种函数类型的指针类型
typedef int(*my_func1) (int, int);
int main(int arg, char** args) {
//1.定义一种函数类型
my_func* p = nullptr;
p = func1;
cout << p(1, 2) << endl;
//2.定义一种指向这种函数类型的指针类型
my_func1 p1 = nullptr;
p1 = func1;
cout << p1(2, 3) << endl;
//3.最常用方法
int(*p2) (int,int) = nullptr;
p2 = func1;
cout << p2(3, 4) << endl;
}
例子:
#include <iostream>
using namespace std;
//定义函数指针
typedef int(*test01)(int);
int printAge(int a) {
return a;
}
void MyPrint(string name,test01 print)
{
cout << "name:" << name << ",Age:" << print(10) << endl;
}
int main() {
MyPrint("aaa", printAge);
}
二.函数指针和函数重载联合使用
例子:
#include <iostream>
using namespace std;
int func1(int a, int b) {
cout << "func1(int,int)" << endl;
return 0;
}
int func1(int a, int b,int c) {//重载
cout << "func1(int,int,int)" << endl;
return 0;
}
int main(int argc,char** argv) {
int(*p3) (int, int) = nullptr;
p3 = func1;
func1(1, 2);
int(*p4) (int, int, int) = nullptr;
p4 = func1;
func1(1, 2, 3);
}