2012-08-13 31 views
2

這可能是一個非常愚蠢的問題,但這是我一直在努力的。在方法中更改LPWSTR之後,它似乎只是針對該特定方法進行更改並在之後立即恢復。我知道全局變量是邪惡的,但這不是我的選擇,因爲它需要更改相當多的代碼。下面是我在做什麼的例子:全球範圍LPWSTR在更改後恢復

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()最終打印出「This should not be here」,而不是「This should be here」。我不完全確定自己做錯了什麼,但是我覺得這是基本的東西,而且在C++中我很生鏽。

回答

5

是的,的確,LPWSTR中的文字是正確的:「這不應該在這裏。」問題是globalStr不是全球性的。它在頭文件中定義爲static,所以每個源文件都有它自己的globalStr副本。在一個源文件中更改它並不會改變其他任何源文件。

爲了修正它,給它在頭一個extern聲明和在一個源文件進行定義:

// Test.h:

的extern LPWSTR globalStr;

// Test.cpp的:

LPWSTR globalStr = L 「這不應該在這裏。」

+0

謝謝,感謝您的快速回復! – 2012-08-13 16:56:31

1

在全局變量上使用static時,它不再是全局變量。它僅在聲明它的翻譯單元(即源文件)中定義。這意味着如果您在頭文件中聲明瞭一個static變量並將其包含在多個源文件中,則每個源填充將分別具有一個唯一變量。

也許你的意思是用extern代替?