您的位置:首页 > 编程语言 > C语言/C++

C++构造与析构(13) - 内建类型的默认构造函数

2015-05-25 00:48 323 查看
参考下面的程序输出:

#include <iostream>
using namespace std;
int main() {
cout << "output = " <<int() << endl;
   return 0;
}
输出结果:

output = 0

如果一个构造函数,没有任何参数,或者每个参数都带有默认值,则此函数是默认构造函数。编译器在需要时会调用此函数(还可能在必要时生成一些额外代码)。

C++甚至允许内建类型拥有默认构造函数。上面代码中,函数风格的int()相当于0. 因此程序打印结果为0.
下面是网络上一些关于内建类型的讨论,这里直接引用过来了:
It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types
have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static
data, no base classes and no virtual functions.
An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in
types are considered to have constructors”.
The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call.
But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: