C ++最烦恼的解析(C++'s most vexing parse again [duplicate])

编程入门 行业动态 更新时间:2024-10-17 23:27:44
C ++最烦恼的解析(C++'s most vexing parse again [duplicate])

直接从http://herbsutter.com/2013/05/09/gotw-1-solution/

虽然widget w(); 对我来说很清楚,我不知道如何下面的代码是一个函数声明?

// same problem (gadget and doodad are types) // widget w( gadget(), doodad() ); // pitfall: not a variable declaration

这怎么可能?

This question already has an answer here:

A confusing detail about the Most Vexing Parse 4 answers

Taken directly from http://herbsutter.com/2013/05/09/gotw-1-solution/

While widget w(); is clear for me, I have no idea how can the below code be a function declaration?

// same problem (gadget and doodad are types) // widget w( gadget(), doodad() ); // pitfall: not a variable declaration

How is this possible?

最满意答案

在函数声明中,类型数组的参数衰减为指向第一个元素的指针,类型函数的参数衰减为函数指针,因此签名将为:

widget w( gadget(*)(), doodad(*)() );

也就是说,一个函数作为第一个参数,指向一个没有参数和返回gadget函数的指针,它将第二个参数指向一个没有参数的函数的指针,并返回一个doodad ,并且该函数本身返回一个widget

还有更有趣或令人困惑的案例,如:

// assume 'x' is a variable defined somewhere: widget w(gadget(x));

怎么能被解释为函数声明? 我的意思是, x是一个变量,对吧? 那么,当声明一个变量你可以添加额外的括号,所以gadget x; 和gadget (x); 都声明相同的变量x 。 这同样适用于函数参数,所以上面的代码看起来像一个函数的声明,它接受名为x的第一个参数,类型为gadget并返回一个widget ...

In a function declaration, arguments of type array decay into pointers to the first element, arguments of type function decay into a function pointer, so the signature would be:

widget w( gadget(*)(), doodad(*)() );

That is, a function that takes as the first argument a pointer to a function taking no arguments and returning gadget, that takes as second argument a pointer to a function taking no arguments and returning a doodad and that the function itself returns a widget

There are even more interesting or confusing cases, like:

// assume 'x' is a variable defined somewhere: widget w(gadget(x));

How could that be interpreted as a function declaration? I mean, x is a variable, right? Well, when declaring a variable you can add extra parenthesis, so gadget x; and gadget (x); both declare the same variable x. The same applies to function arguments so the code above looks like a declaration of a function that takes a first argument named x of type gadget and returns a widget...

更多推荐

本文发布于:2023-08-06 17:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1452800.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:烦恼   vexing   duplicate   parse

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!