C++ 链接静态单例类
当我尝试链接一个单例类a时C++ 链接静态单例类,c++,linker,singleton,C++,Linker,Singleton,当我尝试链接一个单例类a时 sources/singleton.cpp:8:41: error: no se puede declarar que la función miembro ‘static myspace::Singleton& myspace::Singleton::Instance()’ tenga enlace estático [-fpermissive] sources/director.cpp:19:35: error: no se puede declarar
sources/singleton.cpp:8:41: error: no se puede declarar que la función miembro ‘static myspace::Singleton& myspace::Singleton::Instance()’ tenga enlace estático [-fpermissive]
sources/director.cpp:19:35: error: no se puede declarar que la función miembro ‘static void myspace::Singleton::Destroy()’ tenga enlace estático [-fpermissive]
myspace: *** [objects/singleton.o] Error 1
单身人士类别:
#Singleton.h
#include <stdlib.h>
namespace myspace {
class Singleton
{
public:
static Singleton& Instance();
virtual ~Singleton(){};
private:
static Singleton* instance;
static void Destroy();
Singleton(){};
Singleton(const Singleton& d){}
};
}
#Singleton.cpp
#include "../includes/Singleton.h"
namespace myspace {
Singleton* Singleton::instance = 0;
static Singleton& Singleton::Instance()
{
if(0 == instance) {
instance = new Singleton();
atexit(&Destroy);
}
return *instance;
}
static void Singleton::Destroy()
{
if (instance != 0) delete instance;
}
}
#Singleton.h
#包括
命名空间myspace{
单件阶级
{
公众:
静态单例&实例();
虚拟~Singleton(){};
私人:
静态单例*实例;
静态空洞破坏();
Singleton(){};
单例(const Singleton&d){}
};
}
#Singleton.cpp
#包括“./includes/Singleton.h”
命名空间myspace{
Singleton*Singleton::instance=0;
静态单例&单例::实例()
{
if(0==实例){
instance=newsingleton();
退出(销毁);
}
返回*实例;
}
静态void Singleton::Destroy()
{
如果(实例!=0)删除实例;
}
}
我需要一些链接器的LDFLAGS?您需要从cpp文件中的定义中删除
static
:编译器已经从声明中知道Singleton::Instance
和Singleton::Destroy
是static
。其他一切看起来都是正确的。您只能在声明中声明静态方法,而在实现中不允许这样做。只需将您的实现更改为
Singleton& Singleton::Instance()
{
及
你应该很好。提示:在这里发帖以及搜索互联网时,使用英语错误字符串通常是个好主意。在大多数POSIX环境中,可以通过在命令前面加上“LANG=C”来临时请求英语输出。因此,例如
LANG=C make
将为您提供一个很好的可搜索和可邮寄的错误字符串。谢谢@Rawler,我是这方面的新手。我会记住的
void Singleton::Destroy()
{