为什么不能用常量表达式声明数组?

ZSm*_*ain 0 c++ arrays std c++11

我有一个二维的std::array

std::array<std::array<string, n_height>, n_width> data_able;
Run Code Online (Sandbox Code Playgroud)

n_height并且n_width是常量变量,我不知道它们的值是否不同dataTables,并且获取它们的值的唯一可能方法是使用函数调用:

const size_t n_height = dcmI_image->get_height();
const size_t n_width = dcm_image->get_width();
Run Code Online (Sandbox Code Playgroud)

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

error: the value of ‘n_height’ is not usable in a constant expression
 ‘n_height’ was not initialized with a constant expression
Run Code Online (Sandbox Code Playgroud)

当然,对于nWidth也是如此。

Joh*_*nck 5

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

  • @ZSmain-正确:如果在编译时未知大小,则无法创建C样式的数组或`std :: array`。您可以使用`std :: vector`。 (2认同)