执行构造函数时未分配全局常量变量

Global const variables not assigned when constructor is executed

当我尝试在 ProblemClass::ProblemClass() 中使用它时,

MY_GLOBAL_CONST 未分配。为什么?如何解决?我正在处理一个旧的 VC6 MFC 项目。

SomeClass.h

#include "ProblemClass.h"
class SomeClass  
{
private:
    ProblemClass m_problemClass; //created on the heap

public:
    SomeClass();
    ~SomeClass();
}

ProblemClass.h

class ProblemClass
{
public:
    ProblemClass();
    ~ProblemClass();
}

ProblemClass.cpp

#include "ProblemClass.h"
const CString MY_GLOBAL_CONST = _T("User");//Also tried to put that line in ProblemClass.h without luck
ProblemClass::ProblemClass()
{
    CString foo = MY_GLOBAL_CONST; //MFC-Runtime assertion fails, MY_GLOBAL_CONST  is not assigned yet 
}
ProblemClass::~ProblemClass(){}

更新:

经过进一步调查,我可以确认 SomeClass 也在全局上下文中实例化。所以,保罗桑德斯说 "happening here is two global initialisers being executed in the wrong order".

是绝对正确的

看来您在声明中遗漏了 static 关键字。我的全局变量配方需要在 class.

之外初始化

头文件

class ProblemClass
{
public:
    ProblemClass();
    ~ProblemClass();

private:
    static const CString MY_GLOBAL_CONST; // declaration in the header file
}

源文件

const CString ProblemClass::MY_GLOBAL_CONST = _T("HELLO_WORLD"); // Initialization here outside of class

ProblemClass::ProblemClass()
{
    CString foo = MY_GLOBAL_CONST; //MFC-Runtime assertion fails, MY_GLOBAL_CONST  is not assigned yet 
}

// everything else

尝试替换:

const CString MY_GLOBAL_CONST = _T("User");

与:

const TCHAR MY_GLOBAL_CONST [] = _T("User");

后一种构造不需要任何 运行 时间初始化,因此 MY_GLOBAL_CONST 可以依赖于其他初始化代码(因为这里肯定发生的是两个全局初始化程序正在执行顺序错误)。