gpt4 book ai didi

c++ - 是否所有 C++ 编译器都允许使用 static const int 类成员变量作为数组绑定(bind)?

转载 作者:可可西里 更新时间:2023-11-01 16:52:16 25 4
gpt4 key购买 nike

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

 class Class {

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

(请不要告诉我这里使用 std::vector)

这样我就有了一个常量,可以用作数组绑定(bind),稍后在类代码中指定循环语句约束,同时它在其他任何地方都不可见。

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

最佳答案

这是有效的 C++,大多数(全部?)相当现代的编译器都支持它。如果您使用的是 boost,则可以通过 BOOST_STATIC_CONSTANT 宏的形式获得对此功能的可移植支持:

class Class {
private:
BOOST_STATIC_CONSTANT(int, numberOfColors = 16);
COLORREF colors[numberOfColors];
};

如果编译器支持,宏将扩展为 static const int numberOfColors = 16,否则它会求助于 enum { numberOfColors=16 };

关于c++ - 是否所有 C++ 编译器都允许使用 static const int 类成员变量作为数组绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1327806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com