gpt4 book ai didi

c++ - 函数指针作为 C++ 中的参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:31:41 25 4
gpt4 key购买 nike

我对函数指针的参数形式感到困惑。以下两个:

int fun(int (*g)())
{
cout << g() << endl;
}

int fun(int g())
{
cout << g() << endl;
}

这两个定义都适用。但是正如您所注意到的,这两个函数的原型(prototype)存在一些差异:

  • 第一个接受参数int (*g)(),
  • 而第二个采用参数 int g()

我的问题是它们之间有什么区别吗?

最佳答案

在第二种情况下,函数类型调整为指针函数类型,这使得两个函数完全相同。

int fun(int (*g)()); 
int fun(int g()); //same as above, after type adjustment

C++03 标准在 §13.1/3 中说,

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).

[Example:
void h(int());
void h(int (*)()); // redeclaration of h(int())
void h(int x()) { } // definition of h(int())
void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]

它与数组到指针的调整相同,我们更熟悉:

int fun(int *a); 
int fun(int a[]); //same as above, after type adjustment
int fun(int a[10]); //same as above, after type adjustment

都一样!

你可以在这里得到我的详细解答:

关于c++ - 函数指针作为 C++ 中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7459269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com