在C ++中定义静态const变量 [英] Defining static const variable in C++

查看:100
本文介绍了在C ++中定义静态const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的课程:

I have a class like this:

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

在另一个cpp文件中,有类似以下代码:

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

min(ClassA::SIZE, other_variable);

但是,我无法构建此代码,并且出现如下错误(在Mac中最新的cc中OS X,Apple LLVM 4.2(clang-425.0.28))

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" ...

这可能是因为在头文件中定义了 SIZE,并且可以像宏一样使用ClassA .o不包含 SIZE作为符号。同时,在最小模板中使用引用代码时,某种程度上需要符号。 (我可以通过'nm'命令检查ClassA.o不包含 SIZE符号,但是引用代码的目标文件包含 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可以通过在ClassA.cpp中定义文字数来包含 SIZE符号,如下所示:

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

原始代码在某些较旧的编译器(LLVM 4.0)中有效。
解决这个问题有什么好主意吗?

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

推荐答案

您需要提供的定义ClassA :: SIZE ,但在声明时仍给出常数整数值:

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

这篇关于在C ++中定义静态const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆