How to declare a static const char* in your header

2019-03-11 13:25发布

I'd like to define a constant char* in my header file for my .cpp file to use. So I've tried this:

private:
    static const char *SOMETHING = "sommething";

Which brings me with the following compiler error:

error C2864: 'SomeClass::SOMETHING' : only static const integral data members can be initialized within a class

I'm new to C++. What is going on here? Why is this illegal? And how can you do it alternatively?

标签: c++ constants
9条回答
可以哭但决不认输i
2楼-- · 2019-03-11 14:19

You need to define static variables in a translation unit, unless they are of integral types.

In your header:

private:
    static const char *SOMETHING;
    static const int MyInt = 8; // would be ok

In the .cpp file:

const char *YourClass::SOMETHING = "something";

C++ standard, 9.4.2/4:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

查看更多
地球回转人心会变
3楼-- · 2019-03-11 14:19

Constant initializer allowed by C++ Standard only for integral or enumeration types. See 9.4.2/4 for details:

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

And 9.4.2/7:

Static data members are initialized and destroyed exactly like non-local objects (3.6.2, 3.6.3).

So you should write somewhere in cpp file:

const char* SomeClass::SOMETHING = "sommething";
查看更多
Rolldiameter
4楼-- · 2019-03-11 14:25
class A{
public:
   static const char* SOMETHING() { return "something"; }
};

I do it all the time - especially for expensive const default parameters.

class A{
   static
   const expensive_to_construct&
   default_expensive_to_construct(){
      static const expensive_to_construct xp2c(whatever is needed);
      return xp2c;
   }
};
查看更多
登录 后发表回答