Frage

I have a C++ class named Matrix which has a row and column property:

class Matrix
{
public:
    int rows, cols;
    float elements[36];
    // some methods, including constructor
}

I also have a separate function that is supposed to add the elements of two Matrix objects together and return a third Matrix. The code is:

Matrix MatAdd(const Matrix& inMat1, const Matrix& inMat2)
{
    float elements[inMat1.rows*inMat2.cols];  // returns error
    // other code ...
}

The actual error I get is the following (I'm on VS 2013):

error C2057: expected constant expression

I've tried casting inMat1.rows to a const int, but I still get the same error. I must be misunderstanding some core C++ concept, but I haven't been able to find any help by online searches.

Thanks, R.

War es hilfreich?

Lösung

The issue is that you cannot define a variable length array. The length needs to be known at compile time.

A work work around is dynamically allocating the array.

float* elements = new float[inMat1.rows*inMat2.cols];

You will also have to change the elements member of your Matrix class.

Andere Tipps

The size of array should be constant:

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

You can use vector to avoid this error. You can also allocate memory dynamically according to your need.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top