指针设置为null

时间:2017-10-17 16:13:41

标签: c++

代码:

#include <iostream>
class GlobalClass
{

    static GlobalClass *s_instance;

  public:
    static GlobalClass *instance()
    {
        if (!s_instance)
          s_instance = new GlobalClass;
        return s_instance;
    }
    void SetPointer(void *ptr)
    {
        this->PointerSetter(ptr);
        std::cout << "ptr:" << ptr << std::endl;
    }
    void PointerSetter(void *ptr)
    {
        int Value = 1;
        ptr = &Value; 
        std::cout << "ptr:" << ptr << std::endl;
    }
};

GlobalClass *GlobalClass::s_instance = 0;

int main()
{
   void *ptr=NULL;
   std::cout << "ptr:" << ptr << std::endl;
   GlobalClass::instance()->SetPointer(ptr);
   std::cout << "ptr:" << ptr << std::endl;
   return 0;
}

输出:

ptr:0
ptr:0x6ffddc
ptr:0
ptr:0

我无法理解为什么在SetPointer的单例实例中传递给函数GlobalClass的指针反过来传递给PointerSetter的指针在出现时不可见PointerSetter。我需要在main函数中访问它。 如何将指针设置为NULL或0?

0 个答案:

没有答案