问题
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.
回答1:
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;
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.
回答2:
If you don't want it to be constexpr
(and it's not an integer) then you need to initialise it outside of the class body:
class Application
{
private:
static Application* app;
};
Application* Application::app = nullptr;
回答3:
Typically, you need to initialise a static member variable outside the class declaration, unless it is const. I think this explains it better than I could.
回答4:
Static variables do not need to "exist at compile time". But if you want to initialize a static variable inside the class, its value needs to be known at compile time.
However, I do not know the reason for this restriction.
来源:https://stackoverflow.com/questions/19319291/initialisation-of-static-class-member-why-constexpr