簡體   English   中英

C ++中的函數指針語法

[英]function pointer syntax in c++

我只是在學習C ++中的函數指針。 以下示例均進行編譯並返回預期結果,但我被告知示例3是正確的方法。 為什么其他示例仍然有效?

f,g,h,i例子與上面的例子相反,並不是所有的例子都起作用,還有另一件事似乎很奇怪。 與示例1-8相比,它們為什么不起作用?

int executeOperator1(int a, int b, int f(int,int)){
    return f(a,b);
}

int executeOperator2(int a, int b, int f(int,int)){
    return (*f)(a,b);
}
int executeOperator3(int a, int b, int (*f)(int,int)){
    return f(a,b);
}

int executeOperator4(int a, int b, int (*f)(int,int)){
    return (*f)(a,b);
}

int op(int x, int y){
    return x+y;
}


int main(int argc, char *argv[])
{
    int a = 2, b=3;
    //the following 8 examples compile nicely:
    cout << "a=" << a << " b=" << b << " res=" << executeOperator1(a,b,op) <<endl; //1
    cout << "a=" << a << " b=" << b << " res=" << executeOperator2(a,b,op) <<endl; //2
    cout << "a=" << a << " b=" << b << " res=" << executeOperator3(a,b,op) <<endl; //3
    cout << "a=" << a << " b=" << b << " res=" << executeOperator4(a,b,op) <<endl; //4
    cout << "a=" << a << " b=" << b << " res=" << executeOperator1(a,b,&op) <<endl; //5
    cout << "a=" << a << " b=" << b << " res=" << executeOperator2(a,b,&op) <<endl; //6
    cout << "a=" << a << " b=" << b << " res=" << executeOperator3(a,b,&op) <<endl; //7
    cout << "a=" << a << " b=" << b << " res=" << executeOperator4(a,b,&op) <<endl; //8

    //int f(int,int) = op;  //does not compile
    int (*g)(int,int) = op; //does compile
    //int h(int,int) = &op; //does not compile
    int (*i)(int,int) = &op;//does compile
    return 0;
}

您的所有示例都基於出色的所謂的指針衰減規則而起作用。 在幾乎所有上下文中,函數名稱都會衰減為函數的指針。 (此處的衰減表示丟失了原始類型信息,而剩下的僅是指針。在某些情況下,數組的確也會衰減到指針)。

因此,您的所有示例在語義上都是同一件事,我不會將其中的任何一個稱為“ 首選”

只是為了好玩,它也可以編譯:

int executeOperator_insane(int a, int b, int f(int,int)){
    return (***************f)(a,b);
}

與數組一樣,函數作為參數傳遞給函數時,函數也會衰減為指針。 例如:使用兩個int參數並返回int函數將具有int (*) (int, int)
但是您也可以將函數作為引用傳遞,在這種情況下,您將具有int (&) (int, int) 要聲明上述函數指針類型的值,您只需編寫:

typedef int (*FuncType) (int, int);
FuncType myFunc = op; 
// OR
FuncType myFunc = &op;

通常更傾向於采用第二種方式,因為它更加清晰,但是大多數編譯器都讓用戶放棄了第一種方式。

建議通過以下鏈接查看: http : //en.cppreference.com/w/cpp/language/pointer#Pointers_to_functions

使用時:

int f(int,int);

main (或不是函數自變量的任何地方)中,它聲明f為函數,而不是函數的指針。 因此,您不能使用

int f(int,int) = op;

另一方面,

int (*g)(int,int) = op;

聲明g為指向函數的指針。 因此,它起作用。

當將int f(int,int)用作函數的參數時,等效於使用int (*f)(int, int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM