澄清函数转换的指针 [英] Clarification on pointer to a function conversion

查看:77
本文介绍了澄清函数转换的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数类型(左值)可以转换为函数(右值)的指针.

A function type (lvalue) can be converted to a pointer to function (rvalue).

int func();
int (*func_ptr)() = func;

但从(4.1/1)起

可以转换非函数,非数组类型T的左值(3.10) 到右值.

An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue.

这是否意味着未对函数执行从左值到右值的转换?另外,当数组衰减为指针时,它是否不返回作为指针的右值?

Does it mean that a lvalue to rvalue conversion is not done on functions? Also, when an array decays to pointer doesn't it return a rvalue which is a pointer?

推荐答案

函数是左值.指向函数(数据类型)的指针可以是 任何一个;如果给它起一个名字,那就是左值;否则,不是 (粗略地讲).函数指针遵循所有通常的左值 右值转换规则.对于简单类型,例如基本类型或 指针,从左值到右值的转换基本上意味着读取 变量.

Functions are lvalues. A pointer to a function (a data type) can be either; if you give it a name, it's an lvalue; otherwise, it's not (roughly speaking). Pointers to functions obey all of the usual lvalue to rvalue conversion rules. For simple types like the basic types or pointers, the lvalue to rvalue conversion basically means reading the variable.

void func();            //  Declares func
(*(&func))();           //  The expression &func is an rvalue
void (*pf)() = &func;   //  pf is an lvalue
(*pf)();                //  In the expression *pf, pf undergoes an
                        //  lvalue to rvalue conversion

请注意,函数隐式转换为指向的指针. 函数,并且()运算符可同时在两个函数和 指向函数的指针,因此可以写出最后两行:

Note that there is an implicit conversion of function to pointer to function, and that the () operator works on both functions and pointers to functions, so the last two lines could be written:

void (*pf)() = func;
pf();

与往常一样,转换的结果是一个右值(除非 转换为参考类型).当数组时也是如此 隐式转换为指针;数组和函数都只能 作为左值存在,它们都隐式转换为指针, 这是一个右值.但是那个指针可以用来初始化一个 适当的指针类型的变量;这样的变量是左值.

As always, the result of the conversion is an rvalue (unless the conversion is to a reference type). This is also the case when an array is implicitly converted to a pointer; both arrays and functions can only exist as lvalues, but they both implicitly convert to a pointer, which is an rvalue. But that pointer can be used to initialize a variable of the appropriate pointer type; such variables are lvalues.

这篇关于澄清函数转换的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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