本文共 1281 字,大约阅读时间需要 4 分钟。
参考下面的程序输出:
#includeusing namespace std;int main() { cout << "output = " < << 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 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 document.
转载地址:http://qqeji.baihongyu.com/