C++ c+中的单例错误+;
有什么问题C++ c+中的单例错误+;,c++,C++,有什么问题 #include <iostream> using namespace std; class Singleton { public: void HelloWorld(); static Singleton* Instance(){ if (instanza == 0) instanza = new Singleton ; return instanza; }
#include <iostream>
using namespace std;
class Singleton
{
public:
void HelloWorld();
static Singleton* Instance(){
if (instanza == 0)
instanza = new Singleton ;
return instanza;
}
protected:
Singleton();
private:
static Singleton* instanza;
};
Singleton* Singleton:: instanza = 0;
void Singleton::HelloWorld()
{
cout << "Hello World!";
}
int main()
{
Singleton *p = Singleton ::Instance();
p->HelloWorld();
delete p;
}
#包括
使用名称空间std;
单件阶级
{
公众:
void HelloWorld();
静态单例*Instance(){
如果(instanza==0)
instanza=新单态;
返回Instantza;
}
受保护的:
Singleton();
私人:
静态单态*instanceza;
};
Singleton*Singleton::Instantza=0;
void Singleton::HelloWorld()
{
cout HelloWorld();
删除p;
}
g++-Wall-o“singleton”singleton.cpp(nella cartella:/home/tarek/Scrivania/Nuovi codici)
/tmp/ccL8BxOT.o:nella funzione“Singleton::Instance()”:
singleton.cpp:(.text.ZN9Singleton8InstanceEv[ZN9Singleton8InstanceEv]+0x24):riferimento非定义为“singleton::singleton()”
collect2:错误:ld返回了1个退出状态
编译一个fallita。您的构造函数只是声明为未定义 换成
...
protected:
Singleton() {};//add further implementation here
//Singleton() = default; for c++11
...
而且它应该可以工作您需要将构造函数定义为
Singleton::Singleton()
{
}
给我们看英语错误。只需在g++命令前面声明
LANG=C
。消息非常清楚:Singleton::Singleton()
未定义。问题是什么?这是你应该报告的。Stackoverflow不是远程调试服务。你的单例习惯用法被打破了-如果在instanceza=0
之前调用了Instance
?使用单变量的本地静态变量。您忘记编写构造函数定义。话题建议:考虑用Meyers Singleton替换您所拥有的。它可以像static YourType&instance(){static YourType s;returns;}
一样简单。更多完整的讨论请参见此处的顶部答案: