2013-08-18 39 views
2

變得很奇怪的問題...複製 '這個' 指針

我有變量:

Application *ApplicationHandle = NULL; 

在應用程序的功能,我做的:

ApplicationHandle = this; 

而且ApplicationHandle仍然爲NULL。 ..我用調試器檢查這個,在這個操作之前ApplicationHandleNULL,'this'有一些地址,我可以看到這個類的變量這是有效的。操作後ApplicationHandle應與this相同的指針,但它仍然是NULL

這怎麼可能?

+2

你有一個同名的本地和全局變量(ApplicationHandle)嗎?是否有一段代碼將值重新設置爲NULL?與我們分享一段代碼... – user1764961

+0

沒有任何指向我的課程的本地指針,只有這個全局指針。 – Shakaz

+0

你必須粘貼一些代碼。 – Codecat

回答

1

我建議將靜態變量移出全局名稱空間,並將其作爲靜態類成員移入類中。這裏有一個例子:

// 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