函数指针与指针函数大不相同,有时候很容易就搞错,下面总结一下:
1.所谓指针函数就是指返回一个指针的函数,具体格式是: 返回类型* 函数名([参数])
例如:
int *GetData();
不过像这样的函数一般除了库函数中的内存申请及类的内部实现外,不怎么见到,主要是因为在C/C++中一般遵循谁申请的内存谁负责释放的原则。
2.函数指针是指一个指向函数地址的指针,函数指针一般有两种定义方式
2.1 返回类型 (*函数名)(参数表),例如:
#include "stdafx.h"
#include <iostream>
using namespace std;
//两个数相加
int Add(int a, int b)
{
return (a + b);
}
//较大数
int Max(int a, int b)
{
return (a > b ? a : b);
}
//定义函数指针
int (*FuncPtr)(int, int);
int _tmain(int argc, _TCHAR* argv[])
{
FuncPtr = Add; //指向Add
int a = FuncPtr(1, 2); //a = 3
FuncPtr = Max; //指向Max
int b = FuncPtr(1, 2); //b = 2
return 0;
} 这种方式在动态库导出中经常会被用到。
2.2 typedef 返回类型 (*新类型)(参数);例如:
#include "stdafx.h"
#include <iostream>
using namespace std;
//两个数相加
int Add(int a, int b)
{
return (a + b);
}
//较大数
int Max(int a, int b)
{
return (a > b ? a : b);
}
typedef int (*FUNC_CALL)(int, int); //只是定义了接受两个int参数返回int型的新类型
FUNC_CALL FuncPtr = NULL; //具体指向谁还没关联
int _tmain(int argc, _TCHAR* argv[])
{
//int t = FuncPtr(1, 1); //FuncPtr == NULL,错误,还没确定调用谁
FuncPtr = Add; //指向Add
int a = FuncPtr(1, 2); //a = 3
FuncPtr = Max; //指向Max
int b = FuncPtr(1, 2); //b = 2
return 0;
}在上面的这两个函数中,都是接收两个int 的参数,返回值也都是int。定义一个FUNC_CALL的类型,并动态的将FUNC_CALL FuncPtr动态的关联到具体的函数地址里,以实现调用不同的函数。
例子下载地址: http://files.suchone.com/upload/2016/03/20160326013635_78133.zip
本站部分资源收集于网络,纯个人收藏,无商业用途,如有侵权请及时告知!