首页 > 解决方案 > 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()”,而不是我的重载运算符“->”。如果有人可以提供帮助,那就太好了。

谢谢,

影响

标签: c++singletonoverloadingoperator-keyword

解决方案


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;
}

我还更改了您的单例以使用静态函数,这使您的代码线程安全。


推荐阅读