C++ 在C++;
我有一个类,我想要一些值为0,1,3,7,15的位掩码 所以本质上我想声明一个常量int的数组,比如:C++ 在C++;,c++,arrays,constants,declaration,C++,Arrays,Constants,Declaration,我有一个类,我想要一些值为0,1,3,7,15的位掩码 所以本质上我想声明一个常量int的数组,比如: class A{ const int masks[] = {0,1,3,5,7,....} } 但是编译器总是会抱怨 我试过: static const int masks[] = {0,1...} static const int masks[9]; // then initializing inside the constructor 你知道怎么做吗 谢谢 enum Masks
class A{
const int masks[] = {0,1,3,5,7,....}
}
但是编译器总是会抱怨
我试过:
static const int masks[] = {0,1...}
static const int masks[9]; // then initializing inside the constructor
你知道怎么做吗
谢谢
enum Masks {A=0,B=1,c=3,d=5,e=7};
您可能已经想在类定义中修复数组,但不必这样做。数组将在定义点(保留在.cpp文件中,而不是在头文件中)具有完整的类型,在此可以从初始值设定项推断大小
// in the .h file
class A {
static int const masks[];
};
// in the .cpp file
int const A::masks[] = {0,1,3,5,7};
class A {
static const int masks[];
};
const int A::masks[] = { 1, 2, 3, 4, .... };
这是因为不调用方法就无法初始化私有成员。 对于常量和静态数据成员,我总是使用成员初始化列表 如果您不知道成员初始值设定项列表是什么,那么它们正是您想要的 请看以下代码:
class foo
{
int const b[2];
int a;
foo(): b{2,3}, a(5) //initializes Data Member
{
//Other Code
}
}
GCC还有一个很酷的扩展:
const int a[] = { [0] = 1, [5] = 5 }; // initializes element 0 to 1, and element 5 to 5. Every other elements to 0.
这种方法的问题是,我希望能够像使用数组一样使用它。例如,调用值掩码[3]并获取特定掩码。确定。理解。如果你想使用litbs-answer,这就是解决方法。因为在更复杂的情况下,附加而不是预先附加const同样有效,所以我更喜欢这种解决方案。
const int a[] = { [0] = 1, [5] = 5 }; // initializes element 0 to 1, and element 5 to 5. Every other elements to 0.