如何在mfc应用程序的开头初始化变量

时间:2012-08-31 09:43:07

标签: visual-c++ mfc

我有一个std::string对象已在程序的视图类中声明。

//puzzleView.h
public:
   std::string currentState;    // stores the current state of the blocks

我想在执行开始时将其初始化为特定值。但是我在哪里进行初始化?

2 个答案:

答案 0 :(得分:1)

取决于您认为“开始执行”的内容。如果您将此字符串声明为主视图的数据成员,则应在视图类构造函数中初始化它 - 在CPuzzleView::CPuzzleView()函数体中(我假设您的视图类名称为CPuzzleView)。这是最常见的情况:

// #1 Using initialization list
CPuzzleView::CPuzzleView(): currentState("No state")
{
}

// #2 Using assignment in ctor body. Also valid, but case #1 is preferable
CPuzzleView::CPuzzleView()
{
   currentState = "No state";
}

如果您需要在main()函数启动之前对其进行初始化,则应将其声明为static并在任何.cpp文件的全局范围内初始化,例如puzzleView.cpp。但是,不要认为你真的需要这样的教育目的(?)任务。

还要提一下,在MFC / ATL应用程序中使用MFC CString类而不是std::string会更加一致 - 不混合使用不同的字符串类型并避免不必要的转换。

答案 1 :(得分:0)

你必须初始化.cpp文件中的字符串。

相关问题