来源:https://stackoverflow.com/questions/1563897/how-can-you-define-a-static-data-member-of-type-const-stdstring
C++17
Since C++17, you can use an
inline
variable:
// In a header file (if it is in a header file in your case)
class A {
private:
inline static const string RECTANGLE = "rectangle";
};
或者
class A {
private:
static constexpr std::string_view STRING = "some useful string constant";
};
In C++14 and C++11, you can use constexpr const char*
instead of constexpr std::string_view
C++11/C++14
Prior to C++17, you have to define your static member outside the class definition and provide the initializer there.
// In a header file (if it is in a header file in your case)
class A {
private:
static const string RECTANGLE;
};
// In one of the implementation files
const string A::RECTANGLE = "rectangle";