c++ - 全局范围 LPWSTR 在更改后恢复

标签 c++ windows visual-studio-2008 global-variables scope

这可能是一个非常愚蠢的问题,但这是我一直在努力解决的问题。在方法中更改 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/

相关文章:

c++ - 无效函数导致编译器错误 "variable or field ‘funcName’ 声明无效”

c++ - 为 C++ 库创建一个 c 包装器

c++ - 数据文件输入/输出错误

javascript - 控制台写入速度会影响程序执行速度吗

windows - 在 cmd.exe 中执行批处理文件什么都不做

c++ - 带有像素图图像的 QLabel 变得模糊

c# - 检索任何窗口的所有控件及其类型和值

visual-studio-2008 - 在VS2008中调试tt模板

c++ - 从 C++ 样式打印转换为 my_printf()

c# - 在 Winform 中打开 Crystal 报表