0

I have a class defined as

class A{

public :
    A(const int arg){
        x = arg;
    }
    const int x;
    int arr[x][x];
};

but the compiler gives

error : invalid use of non-static data member 'A::x'|

but as I declare x as static const int x

error: array bound is not an integer constant before ']' token|

Any solutions to this.

EDIT : The question has been marked as duplicate of another, but that question is more of concept, it doesn't provide a solution to it. I know the difference but I don't know the solution to the problem except for vectors, which is also mentioned in one of the answers too.

And remove the duplicate flag, since this is different than the post this question is marked as duplicate of.

Thanks.

Nilesh Kumar
  • 343
  • 1
  • 5
  • 18

1 Answers1

0

First of all, no you don't declare x as static const int. Secondly the creation of the arrays is done at compile time while you assign to x at run time.

To solve your problem, use std::vector instead:

struct A {
    std::vector<std::vector<int>> arr;

    A(int arg)
        : arr(arg, std::vector<int>(arg))
    {}
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621