How to initialize a static const member in C++?(如何在 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++ 中初始化静态常量成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中初始化静态常量成员?


基础教程推荐
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01