Karthik Prakash
Karthik Prakash

Reputation: 163

Invalid use of non static data member

class matrix
{
   public:
     int m;
     int n;
     int mat[m][n];
};  

I get this error:

[Error]: Invalid use of non static data member 'matrix::n'
On declaring static:

class matrix
{
   public:
     static int m;
     static int n;
     int mat[m][n];    //Error
};  

I get this error:

[Error]: Array bound is not an integer constant before ']' token
Please tell me what these errors mean and how to fix this problem.

Upvotes: 2

Views: 2805

Answers (2)

Bathsheba
Bathsheba

Reputation: 234665

The sizes of arrays in C++ must be compile-time evaluable.

The compiler doesn't know what to do with int mat[m][n]; since the values of m and n are not known at compile time.

If you want a good reliable matrix class then consider using the BLAS library in Boost. A std::vector<std::vector<int>> can work but it is a jagged-edged matrix with a rather poor memory model.

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409166

The problem is that when you declare mat the member variables m and n doesn't actually exist. They don't exist until you create a an instance of the matrix class. However that won't do much good as arrays in C++ must have a fixed size at the time of compilation.

If you want to set the size of mat at run-time, then the simple solution here is to use a std::vector of std::vector objects.

Like e.g.

std::vector<std::vector<int>> mat;

Upvotes: 2

Related Questions