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()这种格式据我所知出现在两种情况中,一种是在int类型的变量初始化的时候,另一种是在类中定义类型转换运算符(type conversion operator)的时候。不知道题主想问的是哪种,就都简单说一下吧。1.
int类型的变量初始化i1、i2、i3三种写法完全相同。根据标准的意思,对于基本类型
int来说,它不是一个类类型(class type),所以使用圆括号或等号进行初始化的效果是一样的。关于
int i = int();(注:int i();会被当作函数声明)为什么i的值初始化为0的问题,标准中其实已经说了:对于
int类型 value-initialize 的意思就是初始化为0。2. 类型转换运算符
上面三种情况都会调用
X::operator int()把a的类型从X转换成int。至于最早有标准出现是什么时候就不清楚了,题主如果有兴趣可以自己去调查一下:)
没记错的话,c++03,内建类型的值初始化。