C++指向函数的指针
来源:互联网 发布:这个男人来自地球知乎 编辑:程序博客网 时间:2024/06/06 01:16
C++指向函数的指针
函数指针是指指向函数而非指向对象的指针。像其他指针一样,函数指针也指向某个特定的类型。函数类型由其返回类型以及形参表确定,而与函数名无关。
int (*pi)(const string &,const string &);
这个语句将pi申明为指向函数的指针,它所指向的函数带有两个const string& 类型的形参和int类型的返回值。
*pi两侧的园括号是必须的。
int *pi(const string&,const string&);
这个语句声明了一个名为pi的返回值为bool*的函数。
1.使用typedef简化函数指针的定义
函数指针类型相当的冗长。使用typedef定义可以简化。
typedef bool (*pFunc)(const string&,const string&);
该定义表示pFunc是一种指向函数的指针类型的名字。该指针类型为“指向返回bool类型并带有两个const string引用形参的函数的指针”。在要使用这种函数指针类型时,只需要直接使用cmpFcn即可,不必每次都把整个类型声明全部写出来。
2.函数指针的初始化和赋值
在引用函数名但又没有调用该函数时,函数名将会被自动解释为指向函数的指针。假设有函数:
bool lengthCompare(const string &,const string &);
除了作函数调用的左操作数以外,对lengthCompare的所有操作将会被解释为如下类型的指针:
bool (*)(const string&,const string&);
可以用函数名对函数指针做初始化或者赋值:
pFunc p1=0;pFunc p2=lengthCompare;
此时直接使用函数名等于在函数名上做取地址操作。
lengthCompare等于&lengthCompare
3.通过指针调用函数
pFunc pf=lengthCompare;pf("hi","bbbbb");或者(*pf)("hi","dfadsad");
4.函数指针形参
函数的参数是指向函数的指针,可以使用下面的方式来声明
void getCount(int cc,bool(string&,string&));void getCount(int cc,bool (*)(string&,string&));void getCount(int cc,bool (*pf)(string&,string&));
写函数的时候应该如下写
void getCount(int cc,bool (*p)(string&,string&)){}
5.指向重载函数的指针
C++允许使用函数指针指向重载函数:
指针的类型必须与重载函数的一个版本精确匹配,如果没有精确匹配的函数,则对该指针的赋值将导致编译错误。
extern void ff(vector<double>)extern void ff(unsigned int)void (*pf)(unsigned int)=&ff; //ok,第二个 void (*pf1)(int) =&ff; //error,没有精确匹配double (*pf2)(vector<double>)=&ff; //error,返回类型不匹配
下面一段代码:
//指向函数的指针#include <iostream>#include <string>using namespace std;//可以简化定义typedef bool (*cmpFcn)(const string &,const string &);bool lengthCompare(const string &s1,const string &s2){return s1.size() == s2.size();}int main(){ int a = 5;int *pa;//pf是一个指针,指向函数的指针:函数类型//pf是一个局部变量//此*pf必须指向 返回值是bool 参数是(const string &,const string &)bool (*pf)(const string &,const string &); cmpFcn pf2;//pf = &lengthCompare//取地址符号可以省略 因为函数的名称就是指向函数地址的指针pf = lengthCompare;pf2 = lengthCompare;pa = &a;cout << lengthCompare("hello","point") << endl;cout << (*pf)("hello","point") <<endl; cout << (*pf2)("hello","point") <<endl;//调用的时候也可以把*省掉cout << pf("hello","point") <<endl;cout << *pa << endl;return 0;}
阅读全文
1 0
- c 指向函数的指针
- C指向函数指针的函数指针
- C语言指针---指向函数的指针
- 指向函数的指针(摘自C++Primer
- C primer plus:指向函数的指针
- C语言 指向函数的指针
- 指向函数的指针 - C语言
- 11.13 C语言----指向函数的指针
- C语言指向函数的指针
- C语言指向函数的指针
- C语言 指向函数的指针
- C语言指向函数的指针
- C,指向函数的指针,混乱
- C++:指向对象成员函数的指针
- C语言--指向函数的指针
- 11.26C语言----指针函数/指向指针的指针
- 【C++】指向函数的指针与返回指针的函数
- C、C++指向函数的指针(函数指针)浅析
- 阿里巴巴2016 实习生招聘练习题(二)
- MathJax基础(6):间距问题
- zabbix3.2短信告警脚本
- SELinux: Could not downgrade policy file
- Leetcode 115. Distinct Subsequences
- C++指向函数的指针
- 大数据技术贴:构建一个有指导的数据挖掘模型
- 大学计算机基础--4
- 【剑指offer】重建二叉树
- linux系统的引导过程
- Unity复习整理(2)
- 如何写出正确的二分查找?——利用循环不变式理解二分查找及其变体的正确性以及构造方式
- IT之路-编译gcc、调试gdb、makefile.ZCSDN.2017.07.17
- 位运算(2)