c++ - C++ Singleton 用重载运算符实例化-> 可能吗?
问题描述
今天我正在用 C++ 编写一个单例测试用例。单例工作正常,但我想在用户尝试访问它的成员时实例化静态对象,所以如果在我们尝试访问它的成员时没有创建变量,它不会崩溃而是会崩溃只需生成我的单身人士。
这是我的class.h:
class PDG : public EmployeRH
{
public:
static void Instantiate(std::string nom, std::string prenom);
// Current manual instantiation version of the singleton
PDG* operator->();
// This is the line I just added to overload "->" operator ... But it seems it's never called.
void SePresenter();
static PDG* _instance;
private:
PDG();
~PDG();
PDG(std::string nom, std::string prenom);
int _budget;
};
方法.cpp
PDG* PDG::_instance=NULL;
PDG::PDG()
{
}
PDG::~PDG()
{
}
PDG::PDG(std::string a_nom, std::string a_prenom):EmployeRH(a_nom,a_prenom)
{
_budget = 100000;
}
void PDG::Instantiate(std::string a_nom, std::string a_prenom)
{
cout << "instantiation pdg" << endl;
if (_instance == NULL)
{
_instance = new PDG(a_nom,a_prenom);
}
}
PDG* PDG::operator->()
{
PDG::Instantiate("Unknown", "Unknown");
return _instance;
}
void PDG::SePresenter()
{
cout << _nom << " " << _prenom << endl;
}
主文件
void main()
{
PDG::_instance->SePresenter();
system("pause");
}
问题是,它直接进入“SePresenter()”,而不是我的重载运算符“->”。如果有人可以提供帮助,那就太好了。
谢谢,
影响
解决方案
PDG::_instance
是指向 PDG 的指针,因此->
只需取消引用指针,您就不能覆盖该行为。要覆盖->
运算符,您必须直接在类上而不是在指针上调用它:(*PDG::_instance)->SePresenter()
。要保留所需的语法并从取消引用空指针中删除未定义的行为,您可以更改PDG::_instance
为保存实例指针的结构。
#include <string>
#include <iostream>
using namespace std;
struct EmployeRH {
EmployeRH() {}
EmployeRH(std::string nom, std::string prenom) {}
std::string _nom;
std::string _prenom;
};
class PDG : public EmployeRH {
public:
static PDG* Instantiate(std::string nom, std::string prenom);
// Current manual instantiation version of the singleton
void SePresenter();
static struct Instance {
PDG* operator->()
{
return PDG::Instantiate("Unknown", "Unknown");
}
} _instance;
private:
PDG();
~PDG();
PDG(std::string nom, std::string prenom);
int _budget;
};
PDG::Instance PDG::_instance;
PDG::PDG()
{
}
PDG::~PDG()
{
}
PDG::PDG(std::string a_nom, std::string a_prenom)
: EmployeRH(a_nom, a_prenom)
{
_budget = 100000;
}
PDG* PDG::Instantiate(std::string a_nom, std::string a_prenom)
{
static PDG instance(a_nom, a_prenom);
cout << "instantiation pdg" << endl;
return &instance;
}
void PDG::SePresenter()
{
cout << _nom << " " << _prenom << endl;
}
int main()
{
PDG::_instance->SePresenter();
return 0;
}
我还更改了您的单例以使用静态函数,这使您的代码线程安全。
推荐阅读
- python - 将条件放入嵌套列表的函数
- android - 用撇号 android 突出显示搜索词
- python - CircuitPython supervisor.runtime.serial_bytes_available 读取后仍然为 True
- python - Python curses 无法识别终端
- java - 画布上 ImagePattern 的 JavaFX 性能问题
- android - 在添加处理程序以每秒更新单元格后,Android回收器视图在底部跳转
- google-apps-script - Google App Scripts - 使用 google.script.run 的函数调用总是失败
- javascript - 数据表未捕获类型错误:无法读取未定义的属性“添加”(asp.net / js)
- javascript - 函数式编程管道/组合和映射重叠(重构)
- python - Python pdftotext 错误:创建文档时出现 poppler 错误