【问题标题】:Why is it not possible to declare an array with a constant expression?为什么不能用常量表达式声明数组?
【发布时间】:2019-03-05 03:18:09
【问题描述】:

我有一个二维的std::array

std::array<std::array<string, n_height>, n_width> data_able;

n_heightn_width 是常量变量,我不知道它们对于不同dataTables 的值,唯一可能的方法是使用函数调用:

const size_t n_height = dcmI_image->get_height();
const size_t n_width = dcm_image->get_width();

但这是不可能的,这是我得到的错误:

error: the value of ‘n_height’ is not usable in a constant expression
 ‘n_height’ was not initialized with a constant expression

当然,nWidth 也是如此。

【问题讨论】:

  • 它们不仅需要保持不变,而且它们的值必须在编译时已知。即函数 getHeightgetWidth 必须是 constexpr 并在编译时进行评估。
  • “常量表达式”(和相应的关键字constexpr)决定编译时表达式
  • @VTT 我将我的 const 变量的声明更改为 constexpr size_t nHieght = dcmImage-&gt;getHeight(); 但我收到此错误:call to non-constexpr function ‘long unsigned int DicomImage::getHeight() const’ 所以,我猜函数定义必须是一个常量表达式。
  • std::vector 是运行时长度数组的首选容器。如果在编译时不知道您的宽度/高度,请使用它。
  • @0x499602D2 谢谢老兄,我只是想试试,我试试看。

标签: c++ arrays c++11 std


【解决方案1】:

数组的大小必须是常量表达式,例如constexpr 或文字,而不仅仅是const。如果在编译时知道大小,您可以简单地将const 更改为constexpr。如果编译时不知道大小,则不能直接使用std::array

【讨论】:

  • 因此,作为结论,我不能在这些条件下使用std::array
  • @ZSmain -- 对:如果在编译时大小未知,则无法创建 C 样式数组或 std::array。你可以使用std::vector
猜你喜欢
  • 1970-01-01
  • 2022-10-08
  • 2011-11-15
  • 1970-01-01
  • 2015-01-21
  • 2019-07-19
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多