开发者社区> 问答> 正文

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

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

展开
收起
a123456678 2016-03-09 14:54:56 2267 0
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
    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。

    1. 类型转换运算符

    // 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;

    }
    上面三种情况都会调用X::operator int()把a的类型从X转换成int。

    2019-07-17 18:56:09
    赞同 展开评论 打赏
问答分类:
C++
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载

相关实验场景

更多