将对象属性用作数组索引将返回错误(C++)
Use object property as array index returns error (C++)
我有一个名为Matrix
的C++类,它具有行和列属性:
class Matrix
{
public:
int rows, cols;
float elements[36];
// some methods, including constructor
}
我还有一个单独的函数,它应该将两个Matrix
对象的元素添加在一起,并返回第三个Matrix
。代码为:
Matrix MatAdd(const Matrix& inMat1, const Matrix& inMat2)
{
float elements[inMat1.rows*inMat2.cols]; // returns error
// other code ...
}
我得到的实际错误如下(我在VS 2013上):
error C2057: expected constant expression
我尝试过将inMat1.rows
强制转换为const int
,但仍然会出现同样的错误。我一定误解了C++的一些核心概念,但我一直无法通过在线搜索找到任何帮助。
谢谢,R.
问题是不能定义可变长度数组。长度需要在编译时知道。
一个变通办法是动态分配数组。
float* elements = new float[inMat1.rows*inMat2.cols];
您还必须更改Matrix
类的elements
成员。
数组的大小应该是常量:
int a1[10]; //ok
int a2[SIZE]; //ok if the value of SIZE is constant/ computable in compile time
您可以使用矢量来避免此错误。您还可以根据需要动态分配内存。
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'