C++单子实例化与重载操作符->可能吗?

问题描述 投票:0回答:1

今天,我在C++中做一个单例测试,单例工作正常,但我想在用户试图访问静态对象的成员时将其实例化,所以如果当我们试图访问它的成员时,变量没有被创建,它将不会崩溃,而只是生成我的单例。

这是我的class.h.Methods.cpp。

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

main.cpp

void main()
{
PDG::_instance->SePresenter();
system("pause");
}

问题是,它直接进入 "SePresenter()",而不是进入我的重载操作符"->".如果有人能帮忙,那就太好了。

谢谢。

影响力

c++ singleton overloading operator-keyword
1个回答
1
投票

PDG::_instance 是一个指向PDG的指针,所以 -> 只是简单的取消引用指针,你不能覆盖这个行为。要覆盖 -> 操作符,你必须直接在类上调用它,而不是在指针上调用。(*PDG::_instance)->SePresenter(). 为了保持你所期望的语法,并消除从dereferencing the null pointer中的未定义行为,你可以修改 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;
}

我还把你的单子改成了使用函数静态,这使得你的代码线程安全。

© www.soinside.com 2019 - 2024. All rights reserved.