如何在 C++ 中初始化静态常量成员? [英] How to initialize a static const member in C++?

查看:30
本文介绍了如何在 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.

这篇关于如何在 C++ 中初始化静态常量成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆