这可能是一个非常愚蠢的问题,但这是我一直在努力解决的问题。在方法中更改 LPWSTR 后,它似乎只针对该特定方法进行更改,并在之后立即恢复。我知道全局变量是邪恶的,但这不是我的选择,因为它需要更改相当多的代码。这是我正在做的一个例子:
测试.h
static LPWSTR globalStr = L"This shouldn't be here.";
// The ...s are irrelevant code.
class Test {
public:
...
void changeGlobalStr();
void testMethod();
...
...
};
测试.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() 最终打印出“This shouldn't be here”而不是“This should be here”。我不完全确定我做错了什么,但我觉得这是一些基本的东西,而且我的 C++ 非常生疏。
最佳答案
是的,的确,LPWSTR 中的文本是正确的:“这不应该出现在这里。”问题是 globalStr 不是全局的。它在 header 中定义为 static
,因此每个源文件都有自己的 globalStr 拷贝。在一个源文件中更改它不会在任何其他源文件中更改它。
要修复它,请在 header 中给它一个extern
声明,并在一个 源文件中定义它:
//测试.h:
外部 LPWSTR globalStr;
//测试.cpp:
LPWSTR globalStr = L“这不应该在这里。”
关于c++ - 全局范围 LPWSTR 在更改后恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11938552/