I want to use a constant value to initialize member array.
--Test.h--
class Test {
public:
static int ARRAY_SIZE;
...
..
private
int m_array[ARRAY_SIZE];
}
--Test.cpp--
int Test::ARRAY_SIZE = 20;
But, it shows error like this. 'array bound is not an integer constant before ']''
So, I want to know there is a solution for this.
I want fixed size of array. and i don't want any dependency (like additional files for constant value)
What is the best practice for this?
The error is correct. Your array bound is a variable, not a constant.
static int ARRAY_SIZE;
The above declares a variable. The below declares a constant.
static const int ARRAY_SIZE;
For an array's size, there is an additional requirement beyond simply being declared const
: the size must be initialized with a constant expression, also known as a compile-time constant (a constant value known by the compiler). If a translation unit sees the declaration of ARRAY_SIZE
but does not see its value, then it does not count as a compile-time constant. To remedy this, the initialization needs to be in the header file. Combine initialization with declaration:
static const int ARRAY_SIZE = 20;
Since C++11, there has been a fancy way to express that you have a compile-time constant, which you might want to get into the habit of using when it applies:
static constexpr int ARRAY_SIZE = 20;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.