静态类成员的初始化。为什么是constexpr? [英] Initialisation of static class member. Why constexpr?
问题描述
当我想有一个静态指针作为类的成员我需要 constexpr
用于初始化 nullptr
。
when I want to have a static pointer as a member of a class I need constexpr
for 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.
推荐答案
'在类定义内部初始化它。这只允许用于常量积分和枚举类型(always)和 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 b
$ b
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!