【问题标题】:Compiler Error: function call must have a constant value in a constant expression编译器错误:函数调用必须在常量表达式中具有常量值
【发布时间】:2018-07-10 00:46:15
【问题描述】:

VS 给了我一个错误:

 int seam[Image_height(img)];

我真的不明白为什么?每次运行循环时我都需要一个新数组,它的大小由我传入的图像的高度定义。我也包含了它正在调用的函数。

int Image_height(const Image* img) {
    return img->height;
}

void horizontal_carve(Image *img, int newWidth) {

    ...

    int offset = Image_width(img) - newWidth;
    for (int i = 0; i < offset; ++i) {
        int seam[Image_height(img)];

        //do stuff with seam...

    }
}

有人可以解释为什么我会收到错误

function call must have a constant value in a constant expression 

(特别是突出显示“Image_height(img)”)以及我能做些什么来解决它? 谢谢!

【问题讨论】:

  • 使用std::vector
  • 不幸的是,我需要为这个项目使用一个数组,不过谢谢
  • 数组大小必须在编译时知道
  • “很遗憾,我需要为这个项目使用一个数组” 你真的完全确定吗?使用std::vector 是正确的答案,它是一个可变长度数组,它是C++ 的一部分,你可以使用#include &lt;vector&gt;,它不是一个外部库或扩展。如果您想学习 C++,请不要避免。

标签: c++ c++11 visual-c++


【解决方案1】:

C++不支持变长数组,可以使用唯一的ptr

//int seam[Image_height(img)];
std::unique_ptr<int[]> seam(new int[Image_height(img)]); // c++11
auto seam = std::make_unique<int[]>(Image_height(img));  // c++14

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2014-10-21
    • 2021-12-02
    • 2012-07-27
    相关资源
    最近更新 更多