功能指针演示

AKN*_*AKN 2 c++ pointers function-pointers

检查以下代码

int add(int a, int b)
{
    return a + b;
}

void functionptrdemo()
{
    typedef int *(funcPtr) (int,int);
    funcPtr ptr;
    ptr = add; //IS THIS CORRECT?
    int p = (*ptr)(2,3);
    cout<<"Addition value is "<<p<<endl;
}
Run Code Online (Sandbox Code Playgroud)

在我尝试使用相同的函数签名为函数ptr分配函数的地方,它显示编译错误为错误C2659:'=':函数作为左操作数

Ale*_*lis 10

您打算写的内容很可能不是:

typedef int *(funcPtr) (int,int);
Run Code Online (Sandbox Code Playgroud)

但:

typedef int (*funcPtr) (int,int);
Run Code Online (Sandbox Code Playgroud)