高质量程序设计指南c++/c语言(33)--函数指针
函數(shù)類型由其返回類型和形參表確定,而與函數(shù)名無(wú)關(guān)。
// pf points to function returning bool that takes two const string references bool (*pf)(const string &, const string &);*pf兩側(cè)的括號(hào)是必須的
// declares a function named pf that returns a bool * bool *pf(const string &, const string &);1、指向函數(shù)的指針的初始化和賦值
在引用函數(shù)名但是又沒(méi)有調(diào)用該函數(shù)時(shí),函數(shù)名將被自動(dòng)解釋為指向函數(shù)的指針。
bool lengthCompare(const string &, const string &);
除了用作函數(shù)調(diào)用的左操作數(shù)以外,對(duì)lengthCompare的任何使用都將被解釋為如下類型的指針
bool (*)(const string &, const string &);
函數(shù)指針只能通過(guò)同類型的函數(shù)或者函數(shù)指針或者0進(jìn)行初始化和賦值。
cmpFun pf1 = lengthCompare;
cmpFun pf2 = &lengthCompare;
直接引用函數(shù)名等效于在函數(shù)名上應(yīng)用取地址操作符。
2、通過(guò)指針調(diào)用函數(shù)
cmpFun pf = lengthCompare; lengthCompare("hi", "ss"); //direct call pf("ds", "sd"); //pf implicitly dereferenced (*pf)("sss", "sdd"); //pf explicitly dereferenced3、函數(shù)指針形參
可以使用下面的兩種形式
3.1、將形參定義為函數(shù)類型
void useBigger(const string &, const string &, bool (const string &, const string &)); void useBigger(const string &, const string &, bool f(const string &, const string &));注意第三個(gè)形參。
3.2、將形參定義為函數(shù)指針
void useBigger(const string &, const string &, bool (*)(const string &, const string &)); void useBigger(const string &, const string &, bool (*f)(const string &, const string &));4、返回指向函數(shù)的指針
// ff is a function taking an int and return a function pointer // the function pointed to returns an int and takes an int * and int int (* ff(int))(int *, int);閱讀函數(shù)指針聲明的最佳方法就是從聲明的名字開(kāi)始從內(nèi)向外理解。
要理解聲明的定義,首先觀察
ff(int)
將ff聲明為一個(gè)函數(shù),它帶有一個(gè)int型的形參,該函數(shù)返回
int (*)(int *, int);
它是指向函數(shù)的指針。
使用typedef可使該定義簡(jiǎn)明易懂:
typeded int (*PF)(int *, int);
PF ff(int);
允許將形參定義為函數(shù)類型,但是函數(shù)的返回類型則必須是指向函數(shù)的指針,而不能是函數(shù)。
typedef int func(int *, int);//可以理解為把函數(shù)類型 int (int*, int)重命名為funcvoid f1(func); //等價(jià)于void f1(int f(int*,int)), ok: f1 has a parameter of function type func f2(int); // error: f2 has a return type of function type func * f3(int); //ok: f3 returns a pointer to function type5、指向重載函數(shù)的指針
extern void ff(double); extern void ff(unsigned int);void (*pf1)(unsigned int) = &ff; //void (*pf1)(unsigned int) = ff;指針的類型必須與重載函數(shù)的一個(gè)版本精確匹配。如果沒(méi)有精確匹配的函數(shù),則對(duì)該指針的初始化或賦值都將導(dǎo)致編譯錯(cuò)誤:
// error: no match:invalid parameter list void (*pf2)(int) = &ff;// error: no match:invalid return type double (*pf3)(double); pf3 = &ff;?
轉(zhuǎn)載于:https://www.cnblogs.com/zzj3/archive/2013/05/13/3075314.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的高质量程序设计指南c++/c语言(33)--函数指针的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: posix多线程有感--线程高级编程(线
- 下一篇: fixed the link error