我可以从另一个函数中初始化静态成员吗​​?

dan*_*jar 3 c++ static scope initialization member

a中有一个静态成员struct,因为它在析构函数中是必需的.

struct Form
{
    // ...
    ~Form()
    {
        // access World here
    }
    static btDynamicsWorld *World;
};
Run Code Online (Sandbox Code Playgroud)

有没有办法从另一个函数中初始化这个静态成员?

void ModulePhysics::Init()
{
    // ...
    btDynamicsWorld *Form::World = /* ... */;
}
Run Code Online (Sandbox Code Playgroud)

我当前的代码导致这两个编译器错误.

错误1错误C2655:'Form :: World':当前范围内的定义或重新声明非法

错误2错误C2086:'btDynamicsWorld*Form :: World':重新定义

Seb*_*ian 5

不,你不能.但是您可以将其初始化为NULL,并且在函数中,如果它为NULL,则执行实际初始化.

编辑:提供一个示例:

void ModulePhysics::Init()
{
    // ...
    if(Form::World == NULL)
    {
        // The real initialization
    }
}
Run Code Online (Sandbox Code Playgroud)

某处,在文件范围内(在C文件中,而不是在标题中!):

btDynamicsWorld* Form::World = NULL;
Run Code Online (Sandbox Code Playgroud)