c++ - 编译器错误:函数调用必须在常量表达式中具有常量值
问题描述
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++不支持变长数组,可以使用唯一的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
推荐阅读
- terminal - 终端 - 解压缩文件夹中的所有 .gz 文件,而不合并生成的文件
- angularjs - 如果电话号码无效,则阻止表单提交 - Angularjs
- json - 视图上的过滤器应用于视图中排除的过滤器
- c - 带有正则表达式和结构列表的分段错误(核心转储)
- javascript - 函数中的参数使用多个接口中的一个
- mongodb - Mongos 与 Mongod 的兼容性问题
- mongodb - MongoDB 副本集主机名 - 客户端与服务器
- powershell - cmdlet 如何确定它是从作业还是从 RunSpace 调用的?
- python - 在 pandas DataFrame 中选择具有可迭代值之一的行
- javascript - 如何在javascript的嵌套函数中访问父函数的参数?