《我的第一本c++书》学习笔记:STL之函数的相关内容(一)
2013-08-07 11:11
232 查看
一、函数指针的声明与赋值
首先,知道一个函数的函数名表示这个函数的入口地址。如果某个函数指针指向这个函数,则这个入口地址就是函数指针所指向的地址。
定义多个同一类型的指针时,可以用typedef来简化:
这里定义了一种新的函数指针类型PRINTFUNC,表示函数指针类型可以指向一个参数为int,返回值为void的函数。
pPrintFunc = PrintPass;
将函数名传给函数指针,即将入口地址传给指针。
STL为了简化,提供了auto关键字。
利用auto作为函数指针的数据类型来声明一个函数指针。auto会自动定义这种类型。
auto pPrintFunc = PrintPass ;
二、用函数指针调用函数
如果通过回调来实现,这是稍作修改的代码:
最后给出一个链接帮助以后查看:点击打开链接
首先,知道一个函数的函数名表示这个函数的入口地址。如果某个函数指针指向这个函数,则这个入口地址就是函数指针所指向的地址。
//声明一个函数 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; }
最后给出一个链接帮助以后查看:点击打开链接
相关文章推荐
- 《我的第一本c++书》学习笔记:STL之函数的相关内容(二)
- 《我的第一本c++书》学习笔记:STL之函数模板和类模板
- 《我的第一本c++书》学习笔记:STL之vector容器的常用操作函数
- 《我的第一本c++书》学习笔记:STL中函数对象
- STL中vector容器begin(),end(),push_back()等相关函数
- 《我的第一本c++书》学习笔记:STL之迭代器指针的使用注意事项
- sprintf()函数格式内容及相关操作
- 关于函数指针的一些理解与其他相关内容的联想
- STL中与二分查找相关的4个函数
- php数组函数相关内容
- STL - 排序的相关函数
- STL与泛型编程<九>:迭代器相关辅助函数
- 【系统相关】打开WORD2016就弹出:您正试图运行的函数包含有宏或需要宏语言支持的内容...
- VC中加载套接字库的函数相关内容
- Swift的函数与函数指针、闭包Closure等相关内容介绍
- STL之string的相关函数
- STL库中的字符串相关的函数
- Swift的函数与函数指针、闭包Closure等相关内容介绍
- 进程通信函数的相关内容
- 《我的第一本c++书》学习笔记:STL常用头文件和名字空间