问题描述
c++什么时候支持int()/bool()这种写法?有具体的标准解释么?
问题解答
回答1:int()这种格式据我所知出现在两种情况中,一种是在int类型的变量初始化的时候,另一种是在类中定义类型转换运算符(type conversion operator)的时候。不知道题主想问的是哪种,就都简单说一下吧。
1. int类型的变量初始化int i1 = 1;int i2(1);int i3 = int(1);int *pi = new int(1);
i1、i2、i3三种写法完全相同。
From ISO C++11 § 8.5/13
The form of initialization (using parentheses or =) is generally insignificant, but does matter when the initializer or the entity being initialized has a class type; see below. If the entity being initialized does not have class type, the expression-list in a parenthesized initializer shall be a single expression.
根据标准的意思,对于基本类型int来说,它不是一个类类型(class type),所以使用圆括号或等号进行初始化的效果是一样的。
关于int i = int();(注:int i();会被当作函数声明)为什么i的值初始化为0的问题,标准中其实已经说了:
From ISO C++11 § 8.5/16
The semantics of initializers are as follows. ...— If the initializer is (), the object is value-initialized....
对于int类型 value-initialize 的意思就是初始化为0。
2. 类型转换运算符// From ISO C++11 § 12.3.2/1struct X { operator int();};void f(X a) { int i = int(a); i = (int)a; i = a;}
上面三种情况都会调用X::operator int()把a的类型从X转换成int。
至于最早有标准出现是什么时候就不清楚了,题主如果有兴趣可以自己去调查一下:)
回答2:int()> ,这不是函数吗
回答3:没记错的话,c++03,内建类型的值初始化。

