下面我的代码没有针对单例模式进行编译
(错误LNK2019:未解析的外部符号"私人:__thiscall Singleton :: Singleton(无效)"(?? 0Singleton @@ AAE @ XZ)在函数" public:static class Singleton中引用* __cdecl Singleton :: returnOneInstance(void)"(?returnOneInstance @ Singleton @@ SAPAV1 @ XZ))
任何人都可以帮忙吗?我也想知道如何管理记忆?感谢
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Singleton
{
private:
Singleton();
Singleton(const Singleton& sing);
void operator=(const Singleton& sing);
static Singleton* singleton;
/*The 'instance' field holds the reference of the one and only instance.
It is stored in a static variable because its scope has to be the class itself and not a particular instance.
*/
public:
static Singleton* returnOneInstance();
void printme() const;
};
Singleton* Singleton::singleton=NULL;
Singleton* Singleton::returnOneInstance(){
if (!singleton){
singleton=new Singleton;
}
return singleton;
};
void Singleton::printme()const {
cout << "I'm the Singleton" << endl;
}
int main()
{
Singleton* m=Singleton::returnOneInstance();
m->printme();
system("PAUSE");
return 0;
}
答案 0 :(得分:0)
基本上ctr尚未定义。我通过添加{}空体来修复此问题。在这种情况下,你只有一次对象的实例,所以没有内存管理,除非你想释放单例的内存。在这种情况下,您可以提供销毁类并删除保留的内存。
以下是您修改的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Singleton
{
private:
Singleton(){};
Singleton(const Singleton& sing);
void operator=(const Singleton& sing);
static Singleton* singleton;
/*The 'instance' field holds the reference of the one and only instance.
It is stored in a static variable because its scope has to be the class itself and not a particular instance.
*/
public:
static Singleton* returnOneInstance();
void printme() const;
};
Singleton* Singleton::singleton=NULL;
Singleton* Singleton::returnOneInstance()
{
if (!singleton){
singleton=new Singleton;
}
return singleton;
};
void Singleton::printme()const {
cout << "I'm the Singleton" << endl;
}
int main()
{
Singleton* m=Singleton::returnOneInstance();
m->printme();
system("PAUSE");
return 0;
}