Defining static const variable in C++

2019-08-03 05:29发布

I have a class like this:

/* ClassA.h */
class ClassA{
public:
  static const size_t SIZE = 10;
  int array[SIZE];
  funcA();
  funcB();
  ...
};

And, in the other cpp file, there is code like:

min(ClassA::SIZE, other_variable);

But, I cannot build this code, and I get an error like below (in latest cc in Mac OS X, Apple LLVM 4.2 (clang-425.0.28))

Undefined symbols "ClassA::SIZE" ...

It is probably because "SIZE" is defined within the header file and can be used like a macro, ClassA.o does not contain "SIZE" as symbol. At the same time, referring code somehow requires symbol when used inside "min" template. (I can check it by 'nm' command that ClassA.o does not contains "SIZE" symbol, but referring code's object file contains "SIZE" symbol.)

ClassA.o can contains "SIZE" symbol by defining literal number in ClassA.cpp like below:

const int ClassA::SIZE = 10; 

But in this case, there is another error like below, due to an array being defined in header file.

error: fields must have a constant size: 'variable length array in structure' extension will never be supported

The original code worked in some older complier (LLVM 4.0). Any good idea to solve this situation?

标签: c++ class const
3条回答
贪生不怕死
2楼-- · 2019-08-03 05:50
/* ClassA.h */
class ClassA{
public:
  static const size_t SIZE = 10;
  int array[SIZE];
  funcA();
  funcB();
  ...
};
const size_t ClassA::SIZE;

That should work.

查看更多
▲ chillily
3楼-- · 2019-08-03 06:00

Why not use an enum?, you could define the array as a static variable in a static method (so everything is in the header file)

class ClassA {
    public:
    enum {SIZE=10;};
    static int *array() { static int arr[SIZE]; return arr; }
};
查看更多
我只想做你的唯一
4楼-- · 2019-08-03 06:11

You need to provide a definition for ClassA::SIZE, but still give the constant integral value at the point of declaration:

/* ClassA.h */
class ClassA{
public:
  static const size_t SIZE = 10; // value here
  int array[SIZE];
  funcA();
  funcB();
  ...
};


/* ClassA.cpp */
const size_t ClassA::SIZE; // no value here
查看更多
登录 后发表回答