简体   繁体   English

指向c ++中的函数

[英]pointers to functions in c++

It's kinda hard to name a title for my question, so plz pardon me for this ambiguous title. 为我的问题命名标题有点难,所以请原谅我这个含糊不清的标题。

Function names are regarded as the addresses of functions, so we can assign them to function pointers. 函数名称被视为函数的地址,因此我们可以将它们分配给函数指针。

...
void fun(){cout<<"fun called";}  
int main()
{
typedef void (*pf)();
pf p1 = fun;
//Then we can call p1()
p1();
...
}

This is of no problem. 这没问题。 What puzzles me is that pf p2 = &fun; p2(); 令我困惑的是pf p2 = &fun; p2(); pf p2 = &fun; p2(); will do the exact same thing as p1 with no warnings or errors. 将完成与p1完全相同的事情,没有任何警告或错误。

"fun" is the address of the function, so shouldn't &fun be the address of the address of the function? “fun”是函数的地址,所以不应该有趣的是函数地址的地址吗? And when I assign &fun to p2, there should be a type inconsistency, I think. 当我为p2分配和乐趣时,我认为应该存在类型不一致。 Why pf p2 = &fun is a legal assignment? 为什么pf p2 = &fun是合法的作业?

No. 没有。

The id-expression formed by the name of a function decays to the function pointer, except in certain circumstances. 除了在某些情况下,由函数名称形成的id表达式衰减到函数指针。 One of those circumstances is when it is the operand of the address-of operator. 其中一种情况是它是address-of运算符的操作数。 In that case it does not decay, and the result of evaluating the address-of operator on the function name is the address of the function. 在这种情况下,它不会衰减,并且在函数名称上计算运算符地址的结果是函数的地址。

Function names are regarded as the addresses of functions 函数名称被视为函数的地址

"fun" is the address of the function “fun”是函数的地址

Neither of these statements is correct. 这些陈述都不正确。 A function name is not a pointer but a function designator; 函数名称不是指针而是函数指示符; it is only the case that it is - similarly to an array - implicitly converted to a pointer ("decays into a pointer") in some, but not all, contexts, for example, when assigned to an object of type pointer-to-function or when called. 只有这样的情况 - 类似于数组 - 在某些但不是所有的上下文中隐式转换为指针 (“衰减成指针”),例如,当分配给指针类型的对象时功能或被叫时。

This implicit conversion does not happen when the function is the argument of the unary & (address-of) operator, hence &function_name will be of type "pointer to function", and not "pointer-to-pointer-to-function". 当函数是一元& (address-of)运算符的参数时, 不会发生这种隐式转换,因此&function_name的类型为“指向函数的指针”,而不是“指向函数的指针”。

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

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