c++什么时候支持int()/bool()这种写法?有具体的标准解释么?
PHPz
PHPz 2017-04-17 13:39:53
0
3
551

c++什么时候支持int()/bool()这种写法?有具体的标准解释么?

PHPz
PHPz

学习是最好的投资!

reply all(3)
左手右手慢动作

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.

1. Variable initialization of int type

int 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.

2. Type conversion operator

// 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:)

大家讲道理

int()> , isn’t this a function?

Peter_Zhu

If I remember correctly, c++03, value initialization of built-in types.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template