gpt4 book ai didi

c++ - C++单例中的指针和非指针实例

转载 作者:行者123 更新时间:2023-11-28 08:08:43 25 4
gpt4 key购买 nike

我在练习如何制作单例。一切都很顺利,直到我决定玩它。工作版本是:

唱.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();
};

唱.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;
//}

主要.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 行,而错误表明我的构造函数中有错误。你能帮我解决这个问题吗?谢谢大家

最佳答案

您按值返回会生成一个拷贝,该拷贝不起作用,因为您不希望 Singelton 具有复制构造函数。

将其更改为通过引用返回:

GlobalClass  &  GlobalClass::GetInstance()
// ^^^
{
return instance;
}

当你在这里时,你应该确保禁用复制构造函数和赋值运算符

更新你的默认参数在错误的地方。

GlobalClass::GlobalClass(int v = 10)
// ^^^^^ Remove this
{
this->m_value = v;
}


private:
GlobalClass(int v = 10);
// ^^^^^^ Add this

参见:C++ Singleton design pattern

关于c++ - C++单例中的指针和非指针实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9628958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com