Using static const + const as array bound

梦想与她 提交于 2019-12-05 00:05:20

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]; 
}; 
Jim Buck

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.

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