复制'this'指针

时间:2013-08-18 17:23:03

标签: c++

非常奇怪的问题......

我有变量:

Application *ApplicationHandle = NULL;

在应用程序的功能中我做了:

ApplicationHandle = this;

ApplicationHandle仍然保持为NULL ...我正在使用调试器进行检查,此操作ApplicationHandleNULL,并且'此'有一些地址,我可以看到这个类的变量是有效的。操作后ApplicationHandle应与this指针相同,但仍为NULL

怎么可能?

1 个答案:

答案 0 :(得分: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