这种功能如何起作用

How does that kind of function work?

本文关键字:起作用 功能      更新时间:2023-10-16

我发现了一些奇怪的外观功能(希望我称呼正确(,并且无法真正理解其含义。也许您可以帮助我,并说出这是什么意思以及如何使用它?

int (*foo(const unsigned i))(const int, const int)
{
   ... // code
   return some_function;
}

看起来像一个功能指针,但是我看到的指针更像是这样:

void foo(int x, double (*pf)(int)); // function using function pointer as a parameter
double (*pf)(int); // function pointer declaration

谢谢您的时间。

它定义了一个名为 foo的函数,返回 函数指针。

foo采用一个名为 iconst unsigned int参数,并返回一个指针到一个函数,该函数采用两个 const int s并返回 int

这个

int (*foo(const unsigned i))(const int, const int);

是具有名称foo的功能声明,它将指针返回使用类型int(const int, const int)的函数,并具有类型const unsigned int的一个参数。

考虑到您可以删除const预选赛。那是这两个声明

int (*foo(const unsigned i))(const int, const int);

int (*foo(unsigned i))(int, int);

声明相同的一个功能。

您可以使用Typedef名称简化声明。

这是一个指示的程序

#include <iostream>
int (*foo(const unsigned i))(const int, const int);
int bar( int x, int y )
{
    return x + y;
}
int baz( int x, int y )
{
    return x * y;
}
int main() 
{
    std::cout << foo( 0 )( 10, 20 ) << std::endl;
    std::cout << foo( 1 )( 10, 20 ) << std::endl;
    return 0;
}
typedef int ( *fp )( int, int );
fp foo( unsigned i )
{
    return i ? baz : bar;
}

其输出是

30
200

而不是Typedef声明

typedef int ( *fp )( int, int );

typedef int ( *fp )( const int, const int );

您也可以使用别名声明

using fp = int ( * )( int, int );

using fp = int ( * )( const int, const int );

甚至

using fp = int ( * )( const int, int );

using fp = int ( * )( int, const int );