繁体   English   中英

函数指针分配并在C ++中调用?

[英]function pointer assignment and call in c++?

我知道当我们使用函数名称作为值时,该函数会自动转换为指针。 看下面的代码:

int print(int a)
{
    return a;
}

int main()
{
    int (*p)(int) = print;
    int (*q)(int) = &print;

    cout << p(8) << endl;
    cout << (*p)(8) << endl;
}

为什么int (*p)(int) = print; print是一个指针, int (*p)(int) = &print; &print是指向指针的地址,是否等效?

另一方面,当我们使用指向函数的指针来调用该函数时,为什么p(8)(*p)(8)等效的?

print 不是指针。 它的类型是int(int) ,而不是int(*)(int) 这种区别在类型推导中尤其重要

auto& f = print;   //type of f is int(&)(int), not int(*(&))(int)
template<typename Func>
foo(Func& f);
foo(print);  //Func is deduced to be int(int), not int(*)(int)

与数组类似,您不能“按值”复制函数,但可以传递其地址。 例如,

int arr[4];     //the type of arr is int[4], not int*
int *a = arr;   //automatic array-to-pointer decay
int (*a)[4] = &arr;  //type match 
int (*p)(int) = print;  //automatic function-to-pointer decay
int (*p)(int) = &print; //type match

现在,当您通过p调用print时,

p(8)     //automatic dereferencing of p
(*p)(8)  //manual dereferencing of p

print是一个函数,但是可以隐式转换为函数指针类型。 引用cppref

指针功能
函数类型T的左值可以隐式转换为指向该函数的prvalue指针。 这不适用于非静态成员函数,因为引用非静态成员函数的左值不存在。

因此,在您的情况下:

int (*p)(int) = print; // Conversion happens.
int (*q)(int) = &print; // Conversion does not happen.

隐式转换在需要进行程序编译时会自动启动,否则将不应用。

关于函数调用,它是关于内置函数调用operator () 根据cppref ,内置函数调用运算符适用于引用函数的左值表达式和函数指针。 在您的情况下:

p(8); // The function call operator is applied to a pointer to function.
(*p)(8); // The function call operator is applied to an lvalue reference to function.

供您参考(重点是我的):

内置函数调用运算符
一个函数调用表达式,例如E(A1,A2,A3),由一个将函数命名为E的表达式组成,后跟一个括号中的表达式A1,A2,A3 ...的可能为空的列表。 命名函数的表达式可以是

a) 引用函数的左值表达式
b) 函数指针
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM