I have a small C++ program defined below:
class Test
{
   public:
   int a;
   int b[a];
};
When compiling, it produces an error:
testClass.C:7:5: error: invalid use of non-static data member ‘Test::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 learn about what the error message means, and how do I fix it?
You cannot use an array with undefined size in compile time. There are two ways: define a as static const int a = 100; and forget about dynamic size or use std::vector, which is safer than the manual memory management:
class Test
{
public:
  Test(int Num)
    : a(Num)
    , b(Num) // Here Num items are allocated
  {
  }
  int a;
  std::vector<int> b;
};
                        Unless you dynamically allocate them (such as with new[]), arrays in C++ must have a compile-time constant as a size. And Test::a is not a compile-time constant; it's a member variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With