C++ 这种功能是如何工作的?

C++ 这种功能是如何工作的?,c++,C++,我发现了一些奇怪的函数,希望我称之为正确的函数,但不能真正理解它的含义。 也许你能帮我告诉我它到底是什么意思以及如何使用它 int (*foo(const unsigned i))(const int, const int) { ... // code return some_function; } 它看起来像一个函数指针,但我看到的指针更像: void foo(int x, double (*pf)(int)); // function using function pointe

我发现了一些奇怪的函数,希望我称之为正确的函数,但不能真正理解它的含义。 也许你能帮我告诉我它到底是什么意思以及如何使用它

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
谢谢您的时间。

这个

int (*foo(const unsigned i))(const int, const int);
是一个名为foo的函数声明,它返回指向类型为intconst int、const int的函数的指针,并且有一个类型为const unsigned int的参数

考虑到您可能会删除常量限定符。这就是这两项声明

int (*foo(const unsigned i))(const int, const 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;
}
而不是typedef声明

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

您还可以使用别名声明

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

甚至

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

这个

是一个名为foo的函数声明,它返回指向类型为intconst int、const int的函数的指针,并且有一个类型为const unsigned int的参数

考虑到您可能会删除常量限定符。这就是这两项声明

int (*foo(const unsigned i))(const int, const 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;
}
而不是typedef声明

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

您还可以使用别名声明

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

甚至

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


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


foo接受一个名为i的常量无符号int参数,并返回一个指向一个函数的指针,该函数接受两个常量int并返回一个int。

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


foo接受一个名为i的const unsigned int参数,并返回一个指向一个函数的指针,该函数接受两个const int并返回一个int。

对于这样的东西来说是天赐良机。Wow@WhozCraig,不知道这个站点。看起来棒极了。我发现它也适用于C++,相当于:使用F=intconst int,const int;F*fooconst无符号i;像这样的东西真是天赐之物。哇@WhozCraig,我不知道那个网站。看起来棒极了。我发现它也适用于C++,相当于:使用F=intconst int,const int;F*fooconst无符号i;