如何将 C# 中的单例转换为 C++?

How to convert a singleton in c# to c++?

我有这个 C# 代码:

class Animacion
{

    private static Animacion instancia;
    public static Animacion Instance
    {
        get
        {
            if (instancia == null)
            {
                instancia = new Animacion();
            }
            return instancia;
        }
    }

我想将该代码转换为 C++,我尝试使用有形软件解决方案中的代码转换器,我得到了这个:

//.h file code:

class Animacion
{

    private:
        static Animacion *instancia;
    public:
        static Animacion *getInstance() const;
};

//.cpp file code:

Animacion *Animacion::getInstance() const
{
    if (instancia == nullptr)
    {
        instancia = new Animacion();
    }
    return instancia;
}

当我使用转换器生成的代码时,出现如下错误:

error: C2272: 'getInstance' : modifiers not allowed on static member functions

谁能帮帮我?

static Animacion *getInstance() const; 去掉常量。在 C++ 中创建 static class 成员函数 const 毫无意义,因此编译器错误。


C++ 中单例的既定习语看起来也很像:

class Animacion {

private:
    Animacion() {}
    Animacion(const Animacion&) = delete;
    Animacion& operator=(const Animacion&) = delete;
public:
    static Animacion& getInstance() {
        static Animacion theInstance;
        return theInstance;
    }
};

您还应该注意,Singleton 是一个非常有问题的设计模式,您可能没有它也可以生活,而不是为客户端注入接口。这将有助于将实施与使用分离。