13

我正在做这样的事情

类.hpp:

 class Class {

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

类.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++ 标准保证(参见这个 anwser)。但是为什么编译器不将结果static const + const视为常量呢?

4

2 回答 2

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 intenum例如

class Class { 
  enum { arraySize = 384 }; 
  int ar[arraySize+2]; 
}; 
于 2012-01-20T08:35:29.953 回答
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 中。

于 2012-01-20T08:45:27.790 回答