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