简体   繁体   English

为什么这会调用默认构造函数?

[英]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 可以解释为从intX ,或者
  • nothing at all, because 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: 在你的编辑:要获得一个临时的,你有几个选择:

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.

相关问题 为什么调用重载的构造函数会导致调用默认构造函数? - Why does calling an overloaded constructor cause a call of the default constructor? 为什么复制构造函数调用其他类的默认构造函数? - Why does copy constructor call other class' default constructor? 为什么指针 object 没有调用默认构造函数 - Why does the pointer object did not call default constructor 为什么构造函数调用取决于默认析构函数的存在? - Why does the constructor call depend on the default destructor's presence? 为什么空向量调用值类型的默认构造函数? - Why does an empty vector call the value type's default constructor? 为什么要尝试调用默认构造函数? - Why is this attempting to call the default constructor? 为什么这不是“调用'QQmlElement'的隐式删除默认构造函数中的默认构造函数 - Why is this not a default constructor in "Call to implicitly-deleted default constructor of 'QQmlElement' 为什么这会调用复制构造函数,而不是移动构造函数? - Why does this call the copy constructor, not the move constructor? new[] 是否调用 C++ 中的默认构造函数? - Does new[] call default constructor in C++? 为什么用户定义类型的数组必须调用其默认构造函数? - Why does an array of user defined type have to call the default constructor thereof?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM