C ++: how to specify the length of an array with a static constant variable?
I want to declare the length of an array member variable using a constant static class variable. If I do this:
// A.h
#include <array>
using namespace std;
class A {
array<int,LENGTH> internalArray;
public:
const static int LENGTH;
};
// A.cpp
#include "A.h"
constexpr int A::LENGTH{10};
Ah has a bug: "LENGTH" was not declared in this scope "when declaring innerArray.
I find it strange because due to the fact that the class variable, i.e. LENGTH goes out of scope inside a class? The only workaround I found was moving the initialization from A.cpp to Ah:
// A.h
#include <array>
using namespace std;
constexpr int LENGTH{10};
class A {
array<int,LENGTH> internalArray;
public:
const static int LENGTH;
};
But as I understand it, at first they are two different variables: the global scope of the LENGTH namespace and the LENGTH class. In addition, declaring a variable in .h (outside of class A) will create an independent LENGTH object in each translation unit in which the header is included.
Is there a way to specify the length of an array with a static class variable?
source to share
Try the following:
#include <array>
class A {
public:
static const size_t LENGTH = 12;
private:
std::array<int,LENGTH> internalArray;
};
int main(){
A a;
}
You can declare the value to the LENGTH
right in the header of your class, it does not need to be a separate global variable or for it to work in the cpp file.
Use the type size_t
as the template expects std::array
.
If this public / private convention is bad for you, be aware that you can include multiple public / private indicators in the class header.
source to share