[英]Why does this call the default constructor?
struct X
{
X() { std::cout << "X()\n"; }
X(int) { std::cout << "X(int)\n"; }
};
const int answer = 42;
int main()
{
X(answer);
}
I would have expected this to print either 我本来希望这打印
X(int)
, because X(answer);
X(int)
,因为X(answer);
could be interpreted as a cast from int
to X
, or 可以解释为从int
到X
,或者 X(answer);
什么都没有,因为X(answer);
could be interpreted as the declaration of a variable. 可以解释为变量的声明。 However, it prints X()
, and I have no idea why X(answer);
但是, 它打印X()
,我不知道为什么X(answer);
would call the default constructor. 会调用默认构造函数。
BONUS POINTS: What would I have to change to get a temporary instead of a variable declaration? 奖励积分:我需要更改什么才能获得临时而非变量声明?
nothing at all, because X(answer); 什么都没有,因为X(答案); could be interpreted as the declaration of a variable. 可以解释为变量的声明。
Your answer is hidden in here. 你的答案隐藏在这里。 If you declare a variable, you invoke its default ctor (if non-POD and all that stuff). 如果声明一个变量,则调用其默认的ctor(如果是非POD和所有那些东西)。
On your edit: To get a temporary, you have a few options: 在你的编辑:要获得一个临时的,你有几个选择:
(X(answer));
(X)answer;
static_cast<X>(answer)
X{answer};
(C++11) (C ++ 11) []{ return X(answer); }();
(C++11, may incur copy) (C ++ 11,可能会产生副本) void(), X(answer);
X((void(),answer));
true ? X(answer) : X();
if(X(answer), false){}
for(;X(answer), false;);
X(+answer);
The parentheses are optional. 括号是可选的。 What you said is identical to X answer;
你说的与X answer;
相同X answer;
, and it's a declaration statement. ,这是一份声明声明。
如果要声明X类型的变量,则应该这样做:
X y(answer);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.