MY_GLOBAL_CONST
中使用 ProblemClass::ProblemClass()
时未分配。为什么?如何解决?我正在研究一个旧的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
也已在全局上下文中实例化。因此,保罗·桑德斯(Paul Sanders)说“这是两个全局初始化程序以错误的顺序执行”。。
答案 0 :(得分:4)
尝试更换:
const CString MY_GLOBAL_CONST = _T("User");
具有:
const TCHAR MY_GLOBAL_CONST [] = _T("User");
后一种构造不需要任何运行时初始化,因此可以MY_GLOBAL_CONST
依赖于其他初始化代码(因为肯定发生的是两个全局初始化程序以错误的顺序执行)。 / p>
答案 1 :(得分:0)
我好像您在声明中错过了static
关键字。我的gloabl变量配方需要在类外进行初始化。
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