首页 > 解决方案 > 编译器错误:函数调用必须在常量表达式中具有常量值

问题描述

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)”)以及我能做些什么来解决它?谢谢!

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

解决方案


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

推荐阅读