ringa_lee2017-04-17 13:41:53
int()
This format appears in two situations as far as I know, one is when a variable of type int
is initialized, and the other is when the type conversion operator is defined in the class ) time. I don’t know what the questioner wants to ask, so I’ll just say it briefly.
int
typeint i1 = 1;
int i2(1);
int i3 = int(1);
int *pi = new int(1);
i1
, i2
, and i3
are written exactly the same.
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.
According to the meaning of the standard, for the basic type int
, it is not a class type, so the effect of initializing using parentheses or equal signs is the same.
Regarding int i = int();
(Note: int i();
will be treated as a function declaration) why the value of i
is initialized to 0
, the standard has actually said:
From ISO C++11 § 8.5/16
The semantics of initializers are as follows. ...
— If the initializer is (), the object is value-initialized.
...
For int
type value-initialize means to initialize to 0
.
// From ISO C++11 § 12.3.2/1
struct X {
operator int();
};
void f(X a) {
int i = int(a);
i = (int)a;
i = a;
}
In the above three cases, X::operator int()
will be called to convert the type of a
from X
to int
.
As for when the standard first appeared, it is not clear. If you are interested, you can investigate it yourself:)
天蓬老师2017-04-17 13:41:53
If I remember correctly, c++03, value initialization of built-in types.