如何在 C++ 中初始化静态常量成员?

2022-01-05 00:00:00 static c++

是否可以在构造函数之外初始化静态常量值?是否可以在找到成员声明的同一个地方进行初始化?

Is it possible to initialize a static const value outside of the constructor? Can it be initialized at the same place where member declarations are found?

class A {
private:
  static const int a = 4;
  /*...*/
};

推荐答案

是的,您可以,但仅适用于 int 类型.如果您希望您的静态成员是任何其他类型,则必须在 cpp 文件中的某处定义它.

YES you can but only for int types. If you want your static member to be any other type, you'll have to define it somewhere in a cpp file.

class A{
private:
 static const int a = 4; // valid
 static const std::string t ; // can't be initialized here
 ...
 ...
};


// in a cpp file where the static variable will exist 
const std::string A::t = "this way it works";

另外,请注意,此规则已在 C++11 中删除,现在(使用提供该功能的编译器)您可以直接在类成员声明中初始化您想要的内容.

Also, note that this rule have been removed in C++11, now (with a compiler providing the feature) you can initialize what you want directly in the class member declaration.

相关文章