gpt4 book ai didi

c++ - 函数作为函数参数

转载 作者:行者123 更新时间:2023-12-01 14:57:03 25 4
gpt4 key购买 nike

我希望我的格式等没问题,因为这是我第一次发布问题。无论如何,我正在搜索并且找不到解释为什么两个不同的函数定义/声明彼此等效:

#include <iostream> 

using namespace std;

int quadrat( int x )
{
return x*x;
}

void printTable_1( int start, int end, int step, int (*func)( int x ) )
{
for ( int i = start; i <= end; i+=step )
{
cout << i << "\t" << func(i) << '\n';
}
}

void printTable_2( int start, int end, int step, int func( int x ) )
{
for ( int i = start; i <= end; i+=step )
{
cout << i << "\t" << func(i) << '\n';
}
}

int main()
{
printTable_1(1,10,1,quadrat);
printTable_2(1,10,1,quadrat);

return 0;
}
我不明白的是,我没有在函数“printTable_2”中显式定义一个函数指针,就像在函数“printTable_1”中那样,它仍然期望一个。预先感谢您的回答!

最佳答案

这两个定义与编译器相同。有关此行为的粗略概述,请参见Effective STL书,从第20页或PDF第26页开始。

Let's now look at three more function declarations. The first onedeclares a function g taking a parameter that's a pointer to afunction taking nothing and returning a double:

int g(double (*pf)());

Here's another way to say the same thing. The only difference is thatpf is declared using non-pointer syntax (a syntax that's valid in bothC and C++):

int g(double pf()); // same as above; pf is> implicitly a pointer 

As usual, parameter names may be omitted, sohere's a third declaration for g, one where the name pf has beeneliminated:

int g(double ()); // same as above; parameter name is omitted

所以在你的例子中
int (*func)( int x )

int func( int x )
如您所见,它与示例中的方法相同,在该示例中,我们仅省略了 func*的括号。最后,它仍然与编译器完全相同。

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

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