[英]C++ Why do 3 of these constructor calls work, but one doesn't?
I have the following imbecile program: 我有以下不稳定的程序:
#include <iostream>
using namespace std;
class Baz {
public:
Baz() {cout << "Baz ctor " << endl;}
Baz(int i) : Baz() {}
~Baz() {cout << "Baz dtor " << endl;}
};
int main()
{
cout << "w" << endl;
Baz w;
cout << "x" << endl;
Baz x();
cout << "y" << endl;
Baz y(1);
cout << "z" << endl;
Baz z = Baz();
return 0;
}
This produces the following output: 这将产生以下输出:
w
Baz ctor
x
y
Baz ctor
z
Baz ctor
Baz dtor
Baz dtor
Baz dtor
My question is thus: Why don't all these calls invoke the constructor? 因此,我的问题是:为什么所有这些调用都不调用构造函数?
I have been researching, but I have not found an explanation as to why the 2nd call does not invoke the constructor. 我一直在研究,但是还没有找到关于为什么第二个调用不调用构造函数的解释。 I would expect
Baz x()
to be equivalent to Baz x = Baz()
the same way that Baz y(1)
would be equivalent to Baz y = Baz(1)
, there must be something I'm missing. 我希望
Baz x()
等同于Baz x = Baz()
,就像Baz y(1)
等同于Baz y = Baz(1)
,肯定有我缺少的东西。
Your statement Baz x();
您的声明
Baz x();
declares x
as a function with no parameters that returns a Baz
. 将
x
声明为不带参数的函数,该函数返回Baz
。 Change it to Baz x{};
将其更改为
Baz x{};
or Baz x;
或
Baz x;
to call the default constructor. 调用默认构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.