You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何初始化C++类中作为成员的二维整数数组?

问题描述

我有一个名为foo的类,其中成员c被设计为二维整数数组,但无法通过初始化列表正确初始化它。

原代码

49:  class foo{
50:  public: 
51:    int a;
52:    int b;
53:    int** c;
54:    foo(int a_arg, int b_arg, int** c_arg) : a(a_arg),b(b_arg), c(c_arg)
55:    {}
56:  };//end of class
57:  
58:  int main() {
59:    foo bar{5,7, {{1,2,3},{4,5,6},{7,8,9}}  };
60:  }

环境限制

代码将运行在不支持C++标准模板库的嵌入式环境中,无法使用std::vector等容器。

编译报错

仅传入a_arg和b_arg时代码可正常编译,但添加c_arg后,编译器报错:

src/main.cpp:54:3: note: candidate constructor not viable: cannot convert initializer list argument to 'int ** ' foo(int a_arg, int b_arg, int** c_arg) : a(a_arg),b(b_arg), c(c_arg)

尝试情况

显然{{1,2,3},{4,5,6},{7,8,9}}的类型并非int**,我尝试修改c和c_arg的类型修饰符均无效。若第三个参数为int**类型变量,代码可编译,但无法获得预期初始值:

class foo{
  public: 
  int a;
  int b;
  int** c;
  foo(int a_arg, int b_arg, int** c_arg) : a(a_arg),b(b_arg), c(c_arg)
  {}
};//end of class

int main() {
  int** xxx = (int**)malloc(9*sizeof(int));
  foo bar{5,7, xxx  };
}

内容的提问来源于stack exchange,提问作者user4574

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 15:35:48