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

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

问题描述

  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.

    技术原因是用于初始化size的第一个表达式是一个常量表达式,它可以在编译期间计算.这意味着编译器还可以知道数组将有多大,并且可以在编译时完成分配(在这种情况下,保留"可能是更合适的术语).

    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.

    在第二种情况下,表达式不是常量表达式(给定 C++ 定义),并且这种还原是不可能的.

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

    在第二种情况下,值确实在 size 初始化时固定的事实完全无关紧要.规则基于表达式的种类",第二个表达式使用可变变量,因此编译器认为它是非常量的.

    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;
    

    其中涉及 size 的表达式确实相同.

    where the expression involving size is indeed identical.

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

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