【问题标题】:declare a array of const ints in C++在 C++ 中声明一个 const int 数组
【发布时间】:2010-10-30 01:10:38
【问题描述】:

我有一个班级,我想要一些位掩码,其值为 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

知道如何做到这一点吗?

谢谢!

【问题讨论】:

    标签: c++ arrays constants declaration


    【解决方案1】:

    嗯,这是因为你不能在不调用方法的情况下初始化私有成员。 对于 const 和静态数据成员,我总是使用 成员初始化列表

    如果你不知道成员初始化列表是什么,它们就是你想要的。

    看这段代码:

        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.
    

    【讨论】:

      【解决方案2】:
      1. 只能在构造函数或其他方法中初始化变量。
      2. “静态”变量必须在类定义之外进行初始化。

      你可以这样做:

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

      【讨论】:

        【解决方案3】:
        // in the .h file
        class A {
          static int const masks[];
        };
        
        // in the .cpp file
        int const A::masks[] = {0,1,3,5,7};
        

        【讨论】:

        • 由于追加而不是前置 const 也适用于更复杂的情况,我更喜欢这种解决方案。
        【解决方案4】:
        class A {
            static const int masks[];
        };
        
        const int A::masks[] = { 1, 2, 3, 4, ... };
        

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

        【讨论】:

          【解决方案5】:
          enum Masks {A=0,B=1,c=3,d=5,e=7};
          

          【讨论】:

          • 这种方法的问题是我希望能够像数组一样使用它。例如调用一个值 mask[3] 并获取一个特定的掩码。
          • 好的。明白了。那么你想使用 litbs 答案,这就是这样做的方法。
          猜你喜欢
          • 1970-01-01
          • 2020-05-30
          • 2016-05-15
          • 1970-01-01
          • 2010-11-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-15
          相关资源
          最近更新 更多