函式指標是指向函式(而不是一般的陣列,變數)的指標,這個特定的函式由其返回值和形參表決定,與函式名無關:
bool (*pf)(const string &, const string &);
這個語句將 pf 宣告為指向函式的指標,它所指向的函式帶有兩個 const string& 型別的形參和 bool 型別的返回值。
函式指標的定義非常冗長,可以使用typedef來簡化定義:
typedef bool (*cmpfcn)(const string &, const string &);
該定義表示 cmpfcn 是一種指向函式的指標型別的名字。該指標型別為「指向返回 bool 型別並帶有兩個 const string 引用形參的函式的指標」。在要使用這種函式指標型別時,只需直接使用 cmpfcn 即可,不必每次都把整個型別宣告全部寫出來。
在給指標初始化和賦值時,直接使用函式名即可(函式名等效為指向函式的指標),舉個例子:
假設有函式:
bool lengthcompare(const string &, const string &);
則除了用作函式呼叫的左運算元以外,對 lengthcompare 的任何使用都被解釋為如下型別的指標:
bool (*)(const string &, const string &);
所以可以直接用函式名初始化指向函式的指標:
cmpfcn pf1 = 0; // ok: unbound pointer to function
cmpfcn pf2 = lengthcompare; // ok: pointer type matches function's type
pf1 = lengthcompare; // ok: pointer type matches function's type
pf2 = pf1; // ok: pointer types match
注意,指向不同函式型別的指標之間不存在轉換:
string::size_type sumlength(const string&, const string&);
bool cstringcompare(char*, char*);
// pointer to function returning bool taking two const string&
cmpfcn pf;
pf = sumlength; // error: return type differs
pf = cstringcompare; // error: parameter types differ
pf = lengthcompare; // ok: function and pointer types match exactly
有了指向函式的指標以後,我們就可以通過指標呼叫函式了:
cmpfcn pf = lengthcompare;
lengthcompare("hi", "bye"); // direct call
pf("hi", "bye"); // equivalent call: pf1 implicitly dereferenced
(*pf)("hi", "bye"); // equivalent call: pf1 explicitly dereferenced
當乙個函式的返回值為指向函式的指標時,這個函式的定義就會變得很難理解:
int (*ff(int))(int*, int);
從裡向外理解:
ff(int)表明乙個引數為int型別的函式,這個函式返回int (*) (int*,int),這是乙個指向函式的指標。這個指標指向的函式返回值為int型,引數為分為int*型和int型。
利用typedef可以是得定義更加簡潔:
typedef int (*pf)(int*,int);
pf ff(int);
指向函式的指標 函式指標
如果在程式中定義了乙個函式,在編譯時,編譯系統為函式 分配一段儲存空間,這段儲存空間的起始 又稱入口 位址 稱為這個函式的指標。指標即是位址 我們定義乙個指標變數,這個指標變數指向乙個整型資料變數的位址,我們稱指向乙個整型資料的指標變數 那麼它指向乙個函式的位址,稱為指向乙個函式的指標變數。形如 i...
函式指標 指向函式的指標
乙個函式總是占用一段連續的記憶體區域,函式名在表示式中有時也會被轉換為該函式所在記憶體區域的首位址,這和陣列名非常類似。我們可以把函式的這個首位址 或稱入口位址 賦予乙個指標變數,使指標變數指向函式所在的記憶體區域,然後通過指標變數就可以找到並呼叫該函式。這種指標就是函式指標。函式指標的定義形式為 ...
指向函式的指標,指向函式的指標作為函式引數
1.基本法 include pragma warning disable 4996 pragma warning disable 4715 指向函式的指標作為函式的引數 有兩個整數a,b,讓使用者輸入1,2或者3,當輸入1時,給出相對大值,當輸入2時,給出相對小值,當輸入3時,給出兩者之和 1.可以...