2

遇到一个很奇怪的问题...

我有变量:

Application *ApplicationHandle = NULL;

在应用程序的功能我做:

ApplicationHandle = this;

ApplicationHandle仍然是......我NULL正在用调试器检查这个,在这个操作之前ApplicationHandleNULL并且'this'有一些地址,我可以看到这个类的变量是有效的。操作后ApplicationHandle应该是一样的指针this,但还是一样NULL

这怎么可能?

4

1 回答 1

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;
}

可以从任何文件访问静态成员,而不仅仅是包含 line 的文件Test* Test::TestPointer = NULL;。要访问静态指针的内容,请使用Test::TestPointer.

于 2013-08-18T23:56:33.257 回答