C ++ - an array of variables as a member of a class

I have a small C ++ program defined below:

class Test
{
   public:
   int a;
   int b[a];
};

When compiling, an error occurs:

testClass.C:7:5: error: invalid use of non-static data memberTest::a’
testClass.C:8:7: error: from this location
testClass.C:8:8: error: array bound is not an integer constant before ‘]’ token

How do I know what an error message means and how to fix it?

+3
source share
3 answers

You cannot use an array with size undefined at compile time. There are two ways: to determine ahow static const int a = 100;and forget about dynamic size, or to use std::vector, which is safer than managing manual memory:

class Test
{
public:
  Test(int Num)
    : a(Num)
    , b(Num) // Here Num items are allocated
  {
  }
  int a;
  std::vector<int> b;
};
+11
source

If you do not dynamically allocate them (for example, using new[]), arrays in C ++ should have a compile-time constant as size. And is Test::anot a compile-time constant; This is a member variable.

+5

, , , , - , , , , , , - , , , , , - , , , , :

int a;
cin >> a;
int * b = new int[a];

The correct way to declare an array with an unknown size (the size determined at runtime) is to integrate it with your class here, as you do, and remember that any private or public attributes of the class have no memory, just slowdown should never contain any inference otherwise in methods or outside the class, since they are publicly available in your case and, of course, after the declaration of the class instance, for example Test t; in any way here, as you do in class:

class Test
{
public:
int a;
int * p;
Test(int Ia=1) {
    a = Ia;
    b = new int[a];
}
~Test() { delete b; }
};
+1
source

All Articles