C++ static constant string (class member)

I'd like to have a private static constant for a class (in this case a shape-factory). I'd like to have something of the sort.

class A {
   private:
      static const string RECTANGLE = "rectangle";
}

Unfortunately I get all sorts of error from the C++ (g++) compiler, such as:

ISO C++ forbids initialization of member 'RECTANGLE'

invalid in-class initialization of static data member of non-integral type 'std::string'

error: making 'RECTANGLE' static

This tells me that this sort of member design is not compliant with the standard. How do you have a private literal constant (or perhaps public) without having to use a #define directive (I want to avoid the uglyness of data globality!)

Any help is appreciated. Thanks.


You have to define your static member outside the class definition and provide the initializer there.

First

// In a header file (if it is in a header file in your case)
class A {   
private:      
  static const string RECTANGLE;
};

and then

// In one of the implementation files
const string A::RECTANGLE = "rectangle";

The syntax you were originally trying to use (initializer inside class definition) is only allowed with integral and enum types.


在C ++ 11中,你现在可以做到:

class A {
 private:
  static constexpr const char* STRING = "some useful string constant";
};

Inside class definitions you can only declare static members. They have to be defined outside of the class. For compile-time integral constants the standard makes the exception that you can "initialize" members. It's still not a definition, though. Taking the address would not work without definition, for example.

I'd like to mention that I don't see the benefit of using std::string over const char[] for constants. std::string is nice and all but it requires dynamic initialization. So, if you write something like

const std::string foo = "hello";

at namespace scope the constructor of foo will be run right before execution of main starts and this constructor will create a copy of the constant "hello" in the heap memory. Unless you really need RECTANGLE to be a std::string you could just as well write

// class definition with incomplete static member could be in a header file
class A {
    static const char RECTANGLE[];
};

// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";

There! No heap allocation, no copying, no dynamic initialization.

Cheers, s.

链接地址: http://www.djcxy.com/p/17298.html

上一篇: 内存静态函数与成员函数

下一篇: C ++静态常量字符串(类成员)