将对象属性用作数组索引将返回错误(C++)

Use object property as array index returns error (C++)

本文关键字:错误 C++ 返回 数组 对象 属性 索引      更新时间:2023-10-16

我有一个名为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

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