在 C++ 中的类初始化程序中初始化 const 数组

我在 C++ 中有以下类:

I have the following class in C++:

class a {
    const int b[2];
    // other stuff follows

    // and here's the constructor
    a(void);
}

问题是,我如何在初始化列表中初始化 b,因为我无法在构造函数的函数体内初始化它,因为 b 是 const?

The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const?

这不起作用:

a::a(void) : 
    b([2,3])
{
     // other initialization stuff
}

典型的例子是我可以为不同的实例设置不同的 b 值,但已知这些值在实例的生命周期内是恒定的.

The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance.

推荐答案

正如其他人所说,ISO C++ 不支持.但是你可以解决它.只需使用 std::vector 代替.

Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead.

int* a = new int[N];
// fill a

class C {
  const std::vector<int> v;
public:
  C():v(a, a+N) {}
};

相关文章