将对象属性用作数组索引返回错误(C+;+;) 我有一个C++类,名为“代码>矩阵< /COD>,它具有行和列属性: class Matrix { public: int rows, cols; float elements[36]; // some methods, including constructor }

将对象属性用作数组索引返回错误(C+;+;) 我有一个C++类,名为“代码>矩阵< /COD>,它具有行和列属性: class Matrix { public: int rows, cols; float elements[36]; // some methods, including constructor },c++,class,constants,C++,Class,Constants,我还有一个单独的函数,它将两个矩阵对象的元素添加到一起,并返回第三个矩阵。代码是: Matrix MatAdd(const Matrix& inMat1, const Matrix& inMat2) { float elements[inMat1.rows*inMat2.cols]; // returns error // other code ... } 我得到的实际错误如下(我在VS 2013上): 我曾尝试将inMat1.rows强制转换为const i

我还有一个单独的函数,它将两个
矩阵
对象的元素添加到一起,并返回第三个
矩阵
。代码是:

Matrix MatAdd(const Matrix& inMat1, const Matrix& inMat2)
{
    float elements[inMat1.rows*inMat2.cols];  // returns error
    // other code ...
}
我得到的实际错误如下(我在VS 2013上):

我曾尝试将
inMat1.rows
强制转换为
const int
,但仍然出现相同的错误。我一定误解了一些核心C++概念,但是我没有能够通过在线搜索找到任何帮助。 谢谢,
R.

问题在于无法定义可变长度数组。长度需要在编译时知道

解决方法是动态分配阵列

float*elements=newfloat[inMat1.rows*inMat2.cols]


您还必须更改
矩阵
类的
元素
成员。

数组大小应保持不变:

    int a1[10]; //ok
    int a2[SIZE]; //ok if the value of SIZE is constant/ computable in compile time

您可以使用vector来避免此错误。您还可以根据需要动态分配内存。

编译器发出的错误消息很清楚
inMat1.rows*inMat2.cols
不是常量表达式。不能使用它在堆栈上创建
float
s数组。
std::vector元素
float*elements
好得多,它不太容易出错,需要编写的支持代码也少得多。@MattMcNabb感谢您的更正。在C++11中,但不是可变长度数组。
    int a1[10]; //ok
    int a2[SIZE]; //ok if the value of SIZE is constant/ computable in compile time