Initialisation of static class member. Why constexpr?(静态类成员的初始化.为什么是 constexpr?)
问题描述
当我想要一个静态指针作为类的成员时,我需要 constexpr 来使用 nullptr 进行初始化.
when I want to have a static pointer as a member of a class I need constexprfor the initialisation with nullptr.
class Application {
private:
constexpr static Application* app = nullptr;
}
谁能解释我为什么需要这样做?我找不到静态变量必须在编译时存在的确切原因.
Can someone explain me why I need to do that? I cannot find the exact reason why it`s necessary that the static variable has to exist at compile time.
推荐答案
那是因为你在类定义中初始化它.这只允许用于常量整数和枚举类型(总是)和 constexpr 数据成员(自 C++11 起).通常,您会在定义它的位置(在类之外)对其进行初始化,如下所示:
That's because you're initialising it inside the class definition. That's only allowed for constant integral and enumeration types (always) and for constexpr data members (since C++11). Normally, you'd initialise it where you define it (outside the class), like this:
Application.h
class Application {
private:
static Application* app;
}
Application.cpp
Application* Application::app = nullptr;
请注意,即使在 constexpr 情况下,您也需要提供类外定义,但它不能包含初始化程序.不过,我相信第二种情况是您真正想要的.
Note that you need to provide the out-of-class definition even in the constexpr case, but it must not contain an initialiser then. Still, I believe the second case is what you actually want.
这篇关于静态类成员的初始化.为什么是 constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态类成员的初始化.为什么是 constexpr?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
