日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

高质量程序设计指南c++/c语言(33)--函数指针

發布時間:2025/6/17 c/c++ 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 高质量程序设计指南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 &);

typedef bool (* cmpFun)(const string &, const string &); cmpFun pf1 = 0; cmpFun pf2 = lengthCompare; pf1 = lengthCompare; pf2 = pf1;

函數指針只能通過同類型的函數或者函數指針或者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 dereferenced

3、函數指針形參

可以使用下面的兩種形式

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 type

5、指向重載函數的指針

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)--函数指针的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。