所有的C ++编译器允许使用一个静态const int类成员变量作为数组bound? [英] Do all C++ compilers allow using a static const int class member variable as an array bound?

查看:189
本文介绍了所有的C ++编译器允许使用一个静态const int类成员变量作为数组bound?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VC ++中,当我需要为类成员变量指定数组绑定时,这样做:

In VC++ when I need to specify an array bound for a class member variable I do it this way:

 class Class {

 private:
     static const int numberOfColors = 16;
     COLORREF colors[numberOfColors];
 };

(请不要告诉我有关使用std :: vector的信息)

(please don't tell me about using std::vector here)

这种方式我有一个常量,可以用作数组边界,后来在类代码中指定循环语句约束,同时它在其他地方不可见。

This way I have a constant that can be used as an array bound and later in the class code to specify loop-statement constraints and at the same time it is not visible anywhere else.

问题是这个使用 static const int 成员变量只能由VC ++允许,还是通常被其他广泛的编译器允许?

The question is whether this usage of static const int member variables only allowed by VC++ or is it typically allowed by other widespread compilers?

推荐答案

是的,它是100%合法,应该是可移植的。 C ++标准在5.19中描述了这一点 - 常量表达式(强调我的):

Yes, it's 100% legal and should be portable. The C++ standard says this in 5.19 - Constant expressions" (emphasis mine):


在几个地方,C ++需要表达式,或枚举常量:作为数组边界(8.3.4,5.3.4),作为情况表达式(6.4.2),作为位字段长度(9.6),作为枚举器初始值化器(7.2),作为静态成员初始值2),以及作为积分或枚举非类型模板参数(14.3)。

In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case-expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3).

constant-expression:
    conditional-expression

一个整数常量表达式只能包含文字(2.13),枚举器, const使用常量表达式初始化的积分或枚举类型的变量或静态数据成员(8.5),积分或枚举类型的非类型模板参数和sizeof表达式。

An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type template parameters of integral or enumeration types, and sizeof expressions.

也就是说,看起来VC6不支持它。参见 StackedCrooked的回答一个很好的解决方法。事实上,我通常喜欢 enum 方法StackedCrooked提到这种类型的东西。

That said, it appears that VC6 doesn't support it. See StackedCrooked's answer for a good workaround. In fact, I generally prefer the enum method StackedCrooked mentions for this type of thing.

作为一个FYI, static const 在VC9,GCC 3.4.5(MinGW),Comeau和数字火星中工作。

As an FYI, the "static const" technique works in VC9, GCC 3.4.5 (MinGW), Comeau and Digital Mars.

不要忘记,如果你使用static const成员,你会

And don't forget that if you use a "`static const'" member, you'll need a definition for it in addition to the declaration strictly speaking. However, virtually all compilers will let you get away with skipping the definition in this case.

这篇关于所有的C ++编译器允许使用一个静态const int类成员变量作为数组bound?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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