直接从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 answersTaken 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 declarationHow 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...
更多推荐
发布评论