数组初始化使用const的变量在C ++中 [英] Array initialization use const variable in C++

查看:222
本文介绍了数组初始化使用const的变量在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  1. 这可以工作:

  1. this can work:

const int size = 2;
int array[size] = {0}; 


  • 这有编译错误:

  • this has compile error:

    int a = 2;
    const int size = a;
    int array[size] = {0};
    


  • 为什么?

    推荐答案

    由于在C ++委员会的家伙决定左右。

    Because the guys in the C++ committee decided so.

    的技术的原因是被用于初始化大小第一前pression是常数前pression,它可以在编译期间被计算。这意味着,编译器也可以知道该阵列多大将是与分配(在这种情况下的保留可以是更合适的术语)可以在编译时进行。

    The technical reason is that the first expression that is used to initialize size is a constant expression and it can be computed during compilation. This means that the compiler can also know how big the array is going to be and the allocation (in this case "reservation" may be a more appropriate term) can be done at compile time.

    在第二种情况下,而不是前pression不是常数前pression(给定C ++定义)和本revervation是不可能的。

    In the second case instead the expression is not a constant expression (given the C++ definition) and this revervation is not possible.

    这在第二种情况下的价值确实是时间固定事实上尺寸初始化是完全不相干的。规则是对种前pression的,第二个前pression基地采用可变的变量,因此编译器认为非恒定的。

    The fact that in the second case the value is indeed fixed by the time size is initialized is totally irrelevant. The rules are base on the "kind of expression" and the second expression uses mutable variables and thus the compiler considers it non-constant.

    允许对编译时初始化所述第二形式将需要的流分析,因为它可能需要

    Allowing the second form for compile-time initialization would require a flow analysis because it would need to distinguish between

    int a = 2;
    const int size = a;
    

    int a = foo();
    const int size = a;
    

    ,其中前pression涉及尺寸确实是相同的。

    这篇关于数组初始化使用const的变量在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆