对singleton类的多文件访问

multi file access to singleton class

本文关键字:文件 访问 singleton      更新时间:2023-10-16

我有一个singleton类。

在A.h 中

class single
{
    public:
        static single *Instance;
        static single* getInstance()
        { if(!Instance) Instance = new single; 
          return Instance;
        }
        void hello () { cout<<"Hello"; }
    private: single(){ }
}

在A.cpp 中

single *single::Instance = 0;
std::auto_ptr <single> SINGLE_OBJ (single::getInstance());

在B.cpp 中

#include "A.h"
SINGLE_OBJ->hello();

我得到以下错误:未在此作用域中声明SINGLE_OBJ。

要使SINGLE_OBJB.cpp中可见,您应该在A.h.中声明它,即:

extern std::auto_ptr <single> SINGLE_OBJ;

此外,为什么要使用std::auto_ptr,它已被弃用-您应该切换到std::unique_ptr