编译器隐式声明一个默认构造函数

The compiler implicitly declares a default constructor

我正在看课本"C++ Primer Plus, Prata"

第 10 章中的一段引起了我的注意并使我感到困惑。

第 10 章对象和 类:

它说

If you don't provide one, the compiler implicitly declares a default constructor and,...

我觉得应该是

If you don't provide destructor, the compiler implicitly declares a default destructor and,...

段落是否正确?

我该如何正确解释?

谢谢

"one" 部分是正确的。这只是英语语法的细微差别,您可以在句子后面的从属子句中引用某些内容。把它想象成一个前向声明! "default constructor" 部分实际上是一个拼写错误:它应该是 "default destructor",就像你最初想的那样。

应该这样说:

Because a destructor is called automatically when a class object expires, there ought to be a destructor. If you don't provide one [a destructor], the compiler implicitly declares a default destructor and, if it detects code that leads to the destruction of an object, it provides a definition for the destructor.

这里的"one"指的是句子后面的"a destructor,"。理解句子的另一个关键是牢记声明函数和定义函数之间的区别。如果您不提供隐式析构函数,编译器总是声明,但它只会在需要时定义它(也就是说,如果析构函数将被调用)。

更令人困惑的(也可能是导致打字错误的原因)是所有这些对于构造函数同样适用。

让我们看看是否可以改进该段落:

Because the destructor will be called automatically when a class object goes out of scope, all classes must have a destructor. If you don't explicitly provide one, the compiler implicitly declares a default destructor. If the compiler detects code that leads to the destruction of an object, it also provides a default definition for the destructor. The same thing is true for constructors.