1
比方說,我有一個下面的簡單代碼:C++全局變量和初始化順序
Main.cpp的
#include "A.h"
// For several reasons this must be a global variable in the project
A a1;
int _tmain(int argc, _TCHAR* argv[])
{
// Another stuff
return 0;
}
啊
#pragma once
#include <string>
class A
{
private:
// The following works normal if we use simple types like int and etc.
static std::string myString;
public:
A();
};
A. cpp
#include "stdafx.h"
#include "A.h"
// This executes after A::A(), so we are losing all the modifyed content
// If we skip the ="test" part, the string is going to be empty
std::string A::myString = "test";
A::A()
{
// Here myString == ""
myString += "1";
}
的問題是顯而易見的:在這種情況下,我不能在A類的構造函數使用靜態變量,因爲它們不保存更改。雖然我需要它們來處理一些數據。
請給我建議的解決方案。
您的問題都不明顯給我。它看起來像你的代碼會起作用,這取決於你實際上想要做什麼。 – ooga
問題是它應該在輸入A :: A()之前初始化A :: myString。但事實並非如此。我在這裏談論這種設計。我需要首先使A :: myString初始化。 – MixMix