在 C++ 中的类初始化程序中初始化 const 数组 [英] initialize a const array in a class initializer in C++

查看:31
本文介绍了在 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) {}
};

这篇关于在 C++ 中的类初始化程序中初始化 const 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆