使用static const + const作为数组绑定

时间:2012-01-20 08:26:26

标签: c++ arrays qnx

我正在做这样的事情

Class.hpp:

 class Class {

 private:
     static const unsigned int arraySize;
     int ar[arraySize+2];
 };

Class.cpp:

#include <Class.hpp>
const unsigned int arraySize = 384;

编译器(q ++,基于g ++的QNX OS的c ++编译器)在编译包含error: array bound is not an integer constant的单元时给了Class.hpp(而不是在编译Class.cpp时)。

为什么不工作?我知道静态const成员可以用作数组绑定,由C ++标准保证(参见this anwser)。但是为什么编译器不会将static const + const的结果视为常量?

2 个答案:

答案 0 :(得分:13)

这是编译器应该接受的好代码:

class Class { 
  const static int arraySize = 384; 
  int ar[arraySize+2]; 
}; 

如果不是,则编译器坏了。

但是,如果将实际常量从头文件移到选定的翻译单元,则会使代码无效。

// Class.h
class Class { 
  const static int arraySize;
  int ar[arraySize+2]; // ERROR
}; 

// Class.cpp
const int Class::arraySize = 384;

这是因为无法在编译时根据标题中可用的数据确定Class对象的大小。这不是完全正确的原因,但沿着这些行推理有助于理解这样的编译错误。

为避免犯这样的错误,您可以将static const int替换为enum,例如

class Class { 
  enum { arraySize = 384 }; 
  int ar[arraySize+2]; 
}; 

答案 1 :(得分:2)

我很惊讶这实际上是编译gcc,正如评论所说。由于384不在头文件中,因此其他编译单元不知道Class的大小。在某些编译单元中可能无关紧要,具体取决于它们是否使用Class,但我无法想象这个编译:

// this is a source file called, say, blah.cpp
#include <Class.hpp>

void someFunc()
{
    void *mem = malloc(sizeof(Class));  // size is not known, so this can't compile

    // do something with mem
}

你需要拥有.hpp:

class Class {

 private:
     static const unsigned int arraySize = 384;
     int ar[arraySize+2];
 };

..因为它在OP中链接到here

相关问题