一、函数指针的声明与赋值
首先,知道一个函数的函数名表示这个函数的入口地址。如果某个函数指针指向这个函数,则这个入口地址就是函数指针所指向的地址。
//声明一个函数
void PrintPass( int nScore );
//定义函数指针
void (*pPrintFunc)( int nScore );
定义函数指针时也可缩写为:
void (*pPrintFunc)( int );
定义多个同一类型的指针时,可以用typedef来简化:
typedef void (* PRINTFUNC )(int);
PRINTFUNC pFuncFailed;
PRINTFUNC pFuncPass;
这里定义了一种新的函数指针类型PRINTFUNC,表示函数指针类型可以指向一个参数为int,返回值为void的函数。
pPrintFunc = PrintPass;
将函数名传给函数指针,即将入口地址传给指针。
STL为了简化,提供了auto关键字。
利用auto作为函数指针的数据类型来声明一个函数指针。auto会自动定义这种类型。
auto pPrintFunc = PrintPass ;
二、用函数指针调用函数
// 3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintPass( int& nScore )
{
cout<<"分数是:"<<nScore<<" 恭喜通过考试"<<endl;
}
void PrintFailed( int& nScore )
{
cout<<"分数是:"<<nScore<<" 没有通过考试"<<endl;
}
void PrintExcellent( int& nScore )
{
cout<<"分数是:"<<nScore<<" 不错"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int nScore = 22 ;
//定义函数指针
void (*pPrintFunc)( int& );
if ( nScore < 60 )
{
pPrintFunc = PrintFailed;
}
else if( nScore >= 60 && nScore < 100)
{
pPrintFunc = PrintPass;
}
else
{
pPrintFunc = PrintExcellent;
}
(*pPrintFunc)( nScore );
return 0;
}
如果通过回调来实现,这是稍作修改的代码:
// 3.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
typedef void (* PRINTFUNC )(int&);
void PrintMessage( int nScore , PRINTFUNC pFunc )
{
cout<<"==========="<<endl;
(*pFunc)( nScore );
cout<<"+++++++++++"<<endl;
}
void PrintPass( int& nScore )
{
cout<<"分数是:"<<nScore<<" 恭喜通过考试"<<endl;
}
void PrintFailed( int& nScore )
{
cout<<"分数是:"<<nScore<<" 没有通过考试"<<endl;
}
void PrintExcellent( int& nScore )
{
cout<<"分数是:"<<nScore<<" 不错"<<endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
int nScore = 22 ;
//定义函数指针
PRINTFUNC pFunc;
if ( nScore < 60 )
{
pFunc = PrintFailed;
}
else if( nScore >= 60 && nScore < 100)
{
pFunc = PrintPass;
}
else
{
pFunc = PrintExcellent;
}
PrintMessage( nScore, pFunc);
return 0;
}
最后给出一个链接帮助以后查看: 点击打开链接