全局范围LPWSTR在更改后恢复

这可能是一个非常愚蠢的问题,但这是我一直在努力的。 在一个方法中改变了LPWSTR之后,它似乎只是改变了那个特定的方法,并在之后立即恢复。 我知道全局variables是邪恶的,但这不是我的select,因为它需要改变一些代码。 以下是我正在做的一个例子:

Test.h

static LPWSTR globalStr = L"This shouldn't be here."; // The ...s are irrelevant code. class Test { public: ... void changeGlobalStr(); void testMethod(); ... ... }; 

TEST.CPP

 #include "Test.h" Test::changeGlobalStr() { string testString("This should be here."); // I manipulate testString over the next few lines so a variable is necessary. ... BSTR bConversion = _com_util::ConvertStringToBSTR(testString.c_str()); globalStr = bConversion // This prints out the correct output. wcout << "globalStr in changeGlobalStr(): " << globalStr; } 

SecondTest.cpp

 #include "Test.h" Test::testMethod() { changeGlobalStr(); // Get correct output from the print inside the method. wcout << "globalStr in testMethod(): " << globalStr; // Now incorrect output is printed. } 

testMethod()最终打印出“这不应该在这里”,而不是“这应该在这里”。 我不完全确定我在做什么错,但我觉得这是基本的东西,我只是在我的C ++生锈。

是的,的确,在LPWSTR中的文字是正确的:“这不应该在这里。” 问题是globalStr不是全球性的。 它在头文件中被定义为static的,所以每个源文件都有自己的globalStr副本。 在一个源文件中更改它不会改变其他任何源文件。

为了解决这个问题,在头文件中给它一个extern声明,并在一个源文件中定义它:

// Test.h:

extern LPWSTR globalStr;

// Test.cpp:

LPWSTR globalStr = L“这不应该在这里。”

在全局变量上使用static时,它不再是全局的。 它只在声明它的翻译单元(即源文件)中定义。 这意味着如果你在一个头文件中声明了一个static变量,并将其包含在多个源文件中,那么每个源填充将分别具有一个唯一变量。

也许你的意思是使用extern而不是?