为了账号安全,请及时绑定邮箱和手机立即绑定

在C ++中的类初始值设定项中初始化const数组

在C ++中的类初始值设定项中初始化const数组

C++
慕森卡 2019-10-11 11:05:09
我在C ++中有以下课程:class a {    const int b[2];    // other stuff follows    // and here's the constructor    a(void);}问题是,鉴于b不能在构造函数的函数体内进行初始化,因此如何在初始化列表中初始化b const呢?这不起作用:a::a(void) :     b([2,3]){     // other initialization stuff}编辑:恰当的例子是当我可以b为不同的实例使用不同的值时,但已知这些值在实例的生存期内是恒定的。
查看完整描述

3 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

就像其他人说的那样,ISO C ++不支持该功能。但是您可以解决它。只需使用std :: vector即可。


int* a = new int[N];

// fill a


class C {

  const std::vector<int> v;

public:

  C():v(a, a+N) {}

};


查看完整回答
反对 回复 2019-10-11
?
函数式编程

TA贡献1807条经验 获得超9个赞

使用C ++ 11,此问题的答案现已更改,您实际上可以执行以下操作:


struct a {

    const int b[2];

    // other bits follow


    // and here's the constructor

    a();

};


a::a() :

    b{2,3}

{

     // other constructor work

}


int main() {

 a a;

}


查看完整回答
反对 回复 2019-10-11
  • 3 回答
  • 0 关注
  • 577 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信