关于C++中函数定义的一个问题

che*_*eng 13 c c++ function-pointers

我正在阅读一些关于C++中函数指针的资料,并遇到一个我不理解的函数定义.
标准函数定义具有以下形式:

type name (param...)
Run Code Online (Sandbox Code Playgroud)

但以下定义对我来说似乎有点奇怪.有谁可以向我解释一下?谢谢.

float (*GetPtr1(const char opCode)) (float, float)<br>
{
    if(opCode == '+')
        return &Plus;
    else
        return &Minus; // default if invalid operator was passed
}
Run Code Online (Sandbox Code Playgroud)


注意:Plus和Minus是param(float,float)的两个函数,并返回一个浮点数.

Lou*_*nco 16

GetPtr1是一个接受操作码char并返回指向函数的指针的函数.它返回的函数需要两个浮点数并返回一个浮点数.

很多时候,如果你做这样的事情,它会更容易阅读:

typedef float (*FloatOperationFuncPtr) (float, float);

FloatOperationFuncPtr GetPtr1(const char opCode)
{
    if(opCode == '+')
        return &Plus;
    else
        return &Minus; // default if invalid operator was passed
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ode 10

读取毛茸茸声明的规则是从最左边的标识符开始,然后解决问题,记住它()[]在之前绑定*(即,*a[]是一个指针数组,(*a)[]是一个指向数组的指针,是一个*f()返回指针的函数,并且(*f)()是一个指向函数的指针):

        GetPtr1                                       -- GetPtr1
        GetPtr1(                 )                    -- is a function 
        GetPtr1(           opCode)                    -- taking a single parameter named opCode
        GetPtr1(const char opCode)                    -- of type const char
       *GetPtr1(const char opCode)                    -- and returning a pointer
      (*GetPtr1(const char opCode)) (            )    -- to a function
      (*GetPtr1(const char opCode)) (float, float)    -- taking two parameters of type float
float (*GetPtr1(const char opCode)) (float, float)    -- and returning float
Run Code Online (Sandbox Code Playgroud)

因此,如果opCode等于'+',GetPtr1将返回指向该函数的指针Plus,如果它是' - ',它将返回指向该函数的指针Minus.

C和C++声明语法是以表达为中心的(就像Bjarne想要假装的那样); 声明的形式应该与表达式的形式相匹配,因为它将在代码中使用.

如果我们有一个f返回指针的函数,int并且我们想要访问指向的值,我们执行该函数并取消引用结果:

x = *f();
Run Code Online (Sandbox Code Playgroud)

表达式 的类型*f()int,因此函数的声明/定义是

int *f() { ... }
Run Code Online (Sandbox Code Playgroud)

现在假设我们有一个函数f1返回一个指向f上面定义的函数的指针,我们想通过调用来访问该整数值f1.我们需要调用f1,derefence结果(这是函数f),并执行它,然后取消引用结果(因为f返回一个指针):

x = *(*f1())(); // *f1() == f, so (*f1())() == f() and *(*f1())() == *f()
Run Code Online (Sandbox Code Playgroud)

的类型的表达 *(*f1())()int,所以对于decaration /定义f1需要是

int *(*f1())() { return f; }
Run Code Online (Sandbox Code Playgroud)


Bjö*_*lex 5

对于这种情况,总是很高兴知道http://cdecl.org.请注意,只有删除参数名称才能使用它.这就是你得到的float(*GetPtr1(const char ))(float, float):

声明GetPtr1为函数(const char)返回函数指针(float, float)返回float