【发布时间】:2014-04-29 03:43:26
【问题描述】:
我有一个名为 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.
【问题讨论】:
-
编译器的错误信息很清楚。
inMat1.rows*inMat2.cols不是常量表达式。您不能使用它在堆栈上创建floats 数组。