我建議將靜態變量移出全局名稱空間,並將其作爲靜態類成員移入類中。這裏有一個例子:
// test.hpp
#ifndef TEST_HPP
#define TEST_HPP
class Test
{
public:
// Constructor: Assign this to TestPointer
Test(void) { TestPointer = this; }
// This is just a definition
static Test* TestPointer;
private:
unsigned m_unNormalMemberVariable;
};
#endif /* #ifndef TEST_HPP */
上面的代碼本身不能正常工作,你需要聲明的靜態成員變量的實際內存(就像你會爲一個成員函數)。
// test.cpp
#include "test.hpp"
#include <iostream>
// The actual pointer is declared here
Test* Test::TestPointer = NULL;
int main(int argc, char** argv)
{
Test myTest;
std::cout << "Created Test Instance" << std::endl;
std::cout << "myTest Pointer: " << &myTest << std::endl;
std::cout << "Static Member: " << Test::TestPointer << std::endl;
Test myTest2;
std::cout << "Created Second Test Instance" << std::endl;
std::cout << "myTest2 Pointer: " << &myTest2 << std::endl;
std::cout << "Static Member: " << Test::TestPointer << std::endl;
return 0;
}
靜態構件可以來自任何文件訪問,含有該線Test* Test::TestPointer = NULL;
不僅僅是該文件。要訪問靜態指針的內容,請使用Test::TestPointer
。
你有一個同名的本地和全局變量(ApplicationHandle)嗎?是否有一段代碼將值重新設置爲NULL?與我們分享一段代碼... – user1764961
沒有任何指向我的課程的本地指針,只有這個全局指針。 – Shakaz
你必須粘貼一些代碼。 – Codecat