在 C++ 中声明一个 const int 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/928751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:01:10  来源:igfitidea点击:

declare a array of const ints in C++

c++arraysconstdeclaration

提问by Juan Besa

I have a class and I want to have some bit masks with values 0,1,3,7,15,...

我有一堂课,我想要一些值为 0、1、3、7、15 的位掩码,...

So essentially i want to declare an array of constant int's such as:

所以基本上我想声明一个常量 int 数组,例如:

class A{

const int masks[] = {0,1,3,5,7,....}

}

but the compiler will always complain.

但编译器总是会抱怨。

I tried:

我试过:

static const int masks[] = {0,1...}

static const int masks[9]; // then initializing inside the constructor

Any idea on how this can be done?

关于如何做到这一点的任何想法?

Thanks!

谢谢!

回答by Johannes Schaub - litb

class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, ... };

You may want to fixate the array within the class definition already, but you don't have to. The array will have a complete type at the point of definition (which is to keep within the .cpp file, not in the header) where it can deduce the size from the initializer.

您可能想要在类定义中固定数组,但您不必这样做。该数组将在定义点(保留在 .cpp 文件中,而不是在头文件中)具有完整的类型,它可以从初始化程序中推断出大小。

回答by Mr Fooz

// in the .h file
class A {
  static int const masks[];
};

// in the .cpp file
int const A::masks[] = {0,1,3,5,7};

回答by Nick Dandoulakis

  1. you can initialize variables only in the constructor or other methods.
  2. 'static' variables must be initialized out of the class definition.
  1. 您只能在构造函数或其他方法中初始化变量。
  2. “静态”变量必须在类定义之外初始化。

You can do this:

你可以这样做:

class A {
    static const int masks[];
};

const int A::masks[] = { 1, 2, 3, 4, .... };

回答by Ronak Jain

Well, This is because you can't initialize a private member without calling a method. I always use Member Initialization Liststo do so for const and static data members.

嗯,这是因为您不能在不调用方法的情况下初始化私有成员。我总是使用成员初始化列表来为常量和静态数据成员这样做。

If you don't know what Member Initializer Listsare ,They are just what you want.

如果您不知道Member Initializer Lists是什么,那么它们正是您想要的。

Look at this code:

看看这段代码:

    class foo
{
int const b[2];
int a;

foo():    b{2,3}, a(5) //initializes Data Member
{
//Other Code
}

}

Also GCC has this cool extension:

GCC 也有这个很酷的扩展:

const int a[] = { [0] = 1, [5] = 5 }; //  initializes element 0 to 1, and element 5 to 5. Every other elements to 0.

回答by EvilTeach

enum Masks {A=0,B=1,c=3,d=5,e=7};