我正在练习如何制作单身人士。 一切都很顺利,直到我决定玩它。 工作版本是:
sing.hp:
class GlobalClass
{
private:
GlobalClass(int);
int m_value;
static GlobalClass *s_instance;
// static GlobalClass instance;
public:
int get_value();
void set_value(int v);
static GlobalClass *GetS_instance();
// static GlobalClass GetInstance();
};
sing.cpp
#include"sing.hpp"
#include<iostream>
using namespace std;
GlobalClass * GlobalClass::s_instance = 0;
//GlobalClass GlobalClass::instance;
GlobalClass::GlobalClass(int v = 10)
{
this->m_value = v;
}
int GlobalClass::get_value()
{
return this->m_value;
}
void GlobalClass::set_value(int v)
{
this->m_value = v;
}
GlobalClass * GlobalClass::GetS_instance()
{
if (!s_instance)
{
s_instance = new GlobalClass;
}
return s_instance;
}
//GlobalClass GlobalClass::GetInstance()
//{
//
// return instance;
//}
main.cpp中:
#include "sing.hpp"
#include<iostream>
using namespace std;
void foo(void)
{
GlobalClass::GetS_instance()->set_value(1);
cout << "foo: global_ptr is " << GlobalClass::GetS_instance()->get_value() << '\n';
}
int main()
{
cout << "main: global_ptr is " << GlobalClass::GetS_instance()->get_value() << '\n';
foo();
return 1;
}
以上设置运行良好,直到我取消注释我评论的内容: 我收到以下错误:
~/workspace/singleton2$ g++ *.cpp -o dr
sing.cpp:6:27: error: no matching function for call to ‘GlobalClass::GlobalClass()’
sing.cpp:6:27: note: candidates are:
sing.hpp:5:2: note: GlobalClass::GlobalClass(int)
sing.hpp:5:2: note: candidate expects 1 argument, 0 provided
sing.hpp:2:7: note: GlobalClass::GlobalClass(const GlobalClass&)
sing.hpp:2:7: note: candidate expects 1 argument, 0 provided
除了不知道为什么会发生这种情况之外,奇怪的是:第一行错误消息指向我已定义实例的程序中的第6行,而错误表明我的构造函数中存在错误。 你能帮我解决一下这个问题吗? 谢谢大家
答案 0 :(得分:1)
按值返回,这会生成一个副本,因为您不希望Singeltons具有复制构造函数。
将此更改为引用返回:
GlobalClass & GlobalClass::GetInstance()
// ^^^
{
return instance;
}
当你在这里时,你应该确保禁用复制构造函数和赋值运算符
GlobalClass::GlobalClass(int v = 10)
// ^^^^^ Remove this
{
this->m_value = v;
}
private:
GlobalClass(int v = 10);
// ^^^^^^ Add this