- 函数指针的主要用途是函数的回调
函数的二进制代码存放在内存四区中的代码段,,函数的地址是它在内存中的起始地址。如果把函数的地址作为参数传递给函数,就可以在函数中灵活调用其他函数。
使用函数指针的三个步骤:
(a)声明函数指针;
(b)让函数指针指向函数的地址;
(c)通过函数指针调用函数;
(1)声明函数指针
声明普通指针时,必须提供指针的类型,同样,声明函数指针时,也必须提供函数的类型,函数的类型包括返回值和参数列表(函数名和形参名不属于函数的类型)。
假设函数的原型是:
int func1(int bianhao,string message);
int func2(int no,string str);
int func3(int id,string info);
bool func4(int id,string info);
bool func5(int id);
那么func1 func2 func3就是相同类型的函数,形参的变量名不同没有关系,func4和func5又是另外两种不同类型的函数,这三种类型的函数指针声明分别如下:
int (*pfa)(int,string); (写成int (*pfa)(int no,string str)也可以,变量名用什么名字都无所谓)
bool (*pfb)(int,string);
bool (*pfc)(int);
// PointerTest13.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void func1(int no, string message)
{
cout << no << "号你好,我是" << message << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int bh = 3;
string str = "秀莲";
//普通的调用方法
func1(bh,str);
//函数指针的调用方法
//1、声明函数指针
void(*pfun1)(int,string);
//2、对函数指针赋值,在c++中,函数名就是函数的地址
pfun1 = func1;
//3、用函数指针名来调用函数
pfun1(bh,str);//这是C++的写法
(*pfun1)(bh, str);//这是C语言的写法,在c++也可以用
system("pause");
return 0;
}
2. 指针函数的应用场景--回调函数
void 个性化函数()
{
//个性化函数代码
}
void 通用函数(个性化函数指针p)
{
//通用函数代码段1
//个性化函数指针p();
//通用函数代码段2
}
在通用函数中,形参用函数指针接收传进来的地址
案例1:给回调函数从调用者函数内部传参
// PointerTest13.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void func1(int no, string message)
{
cout << no << "号你好,我是" << message << endl;
}
void func2(void (*pfun)(string str),int no)//通用函数
{
cout << "我是" << no << "号" << endl;
cout <<"通用函数前半部分" << endl;
string str = "YoYo";//从调用者函数内部传参
pfun(str);
cout << "通用函数后半部分" << endl;
}
void func3(string str)//个性化函数1
{
cout << "我是个性化函数1,我叫" <<str << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
//int bh = 3;
//string str = "秀莲";
普通的调用方法
//func1(bh,str);
函数指针的调用方法
1、声明函数指针
//void(*pfun1)(int,string);
2、对函数指针赋值,在c++中,函数名就是函数的地址
//pfun1 = func1;
3、用函数指针名来调用函数
//pfun1(bh,str);//这是C++的写法
//(*pfun1)(bh, str);//这是C语言的写法,在c++也可以用
//指针函数的应用场景--回调函数
void(*pf1)(string);
pf1 = func3;
func2(pf1, 33);
system("pause");
return 0;
}
案例2:从调用者函数外部传参
// PointerTest13.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void func1(int no, string message)
{
cout << no << "号你好,我是" << message << endl;
}
void func2(void (*pfun)(string str),int no,string str)//通用函数
{
cout << "我是" << no << "号" << endl;
cout <<"通用函数前半部分" << endl;
//string str = "YoYo";//从调用者函数内部传参
pfun(str);
cout << "通用函数后半部分" << endl;
}
void func3(string str)//个性化函数1
{
cout << "我是个性化函数1,我叫" <<str << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
//int bh = 3;
//string str = "秀莲";
普通的调用方法
//func1(bh,str);
函数指针的调用方法
1、声明函数指针
//void(*pfun1)(int,string);
2、对函数指针赋值,在c++中,函数名就是函数的地址
//pfun1 = func1;
3、用函数指针名来调用函数
//pfun1(bh,str);//这是C++的写法
//(*pfun1)(bh, str);//这是C语言的写法,在c++也可以用
//指针函数的应用场景--回调函数
void(*pf1)(string);
pf1 = func3;
string str = "YoYo";
func2(pf1, 33,str);//从调用者函数外部传参
system("pause");
return 0;
}