函数指针分配并在C ++中调用? [英] function pointer assignment and call in c++?

查看:102
本文介绍了函数指针分配并在C ++中调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know when we use the name of a function as a value, the function is automatically converted to a pointer. look at following code:

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 是指向指针的地址(等效)?

why are int (*p)(int) = print; , print is a pointer, and int (*p)(int) = &print;, &print is an address to a pointer, equivalent?

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

On the other hand, when we use a pointer to a function to call the function, why are p(8) and (*p)(8) equivalent?

推荐答案

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

print is a function, but it is implicitly convertible to a function pointer type. Quoted from cppref:

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

Function to pointer
An lvalue of function type T can be implicitly converted to a prvalue pointer to that function. This does not apply to non-static member functions because lvalues that refer to non-static member functions do not exist.

所以,在您的情况下:

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

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

Implicit conversion kicks in automatically when it is needed to make the program compile, and is not applied otherwise.

关于函数调用,它与内置函数调用运算符()有关.根据 cppref ,内置函数调用运算符适用于两个左值表示函数和函数指针的表达式.就您而言:

With respect to function calling, it is about the built-in function call operator (). According to cppref, the built-in function call operator is applicable to both an lvalue expression that refers to a function and a pointer to function. In your case:

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.

供您参考(重点为我):

For your reference (emphasis mine):

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

Built-in function call operator
A function call expression, such as E(A1, A2, A3), consists of an expression that names the function, E, followed by a possibly empty list of expressions A1, A2, A3, ..., in parentheses. The expression that names the function can be

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

a) lvalue expression that refers to a function
b) pointer to function
...

这篇关于函数指针分配并在C ++中调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆