开发者

Function pointer demo

Check the below code

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 "&开发者_Python百科lt;<p<<endl;
}

In the place where I try to assign a function to function ptr with same function signature, it shows a compilation error as error C2659: '=' : function as left operand


It is very likely that what you intended to write was not:

typedef int *(funcPtr) (int,int);

but:

typedef int (*funcPtr) (int,int);


Alex answer is correct. But the good practice will be

ptr = &add;

if you write like this below:

ptr = add;

it is the compiler which assumes that you wanted to store the address of the function add. So better let's not make the compiler to assume.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜