Using static const + const as array bound

心不动则不痛 提交于 2019-12-10 01:14:11

问题


I'm doing something like this

Class.hpp:

 class Class {

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

Class.cpp:

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

The compiler (q++, a c++ compiler for the QNX OS based on g++) gives me error: array bound is not an integer constant while compiling a unit including Class.hpp (not while compiling Class.cpp).

Why isn't that working? I know that a static const member can be used as an array bound, guaranteed by the C++ standard (see this anwser). But why doesn't the compiler see the result of static const + const as a constant?


回答1:


This is good code which should have been accepted by the compiler:

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

and if it isn't, your compiler is broken.

However, if you move actual constant out of the header file to selected translation unit, that invalidates the code.

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

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

This is because the size of your Class object cannot be determined at compile time from the data available in the header alone. This is not exactly right reason, but reasoning along these lines helps to understand compilation errors such as this.

To avoid making such mistakes, you can replace static const int with an enum, e.g.

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



回答2:


I'm surprised this actually compiles on gcc, as a comment says. Since the 384 isn't in the header file, the size of the Class is not known to other compilation units. It might not matter in some compilation units depending on how/if they are using Class, but I can't imagine this compiling:

// 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
}

You need to have in your .hpp:

class Class {

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

.. as it is in the OP that you link to here.



来源:https://stackoverflow.com/questions/8938574/using-static-const-const-as-array-bound

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!