在 C++ 中调用单例对象的正确方法

Men*_*des 0 c++ singleton

我已经根据此处发布的命中构建了一个单例类。

我用一个getMessage()函数扩展了它,该函数将检索内部字典消息 - 字典只需要在整个应用程序上加载一次,这就是单例的原因。

我的代码:

单例.hpp

class Singleton {

public:

    static Singleton& getInstance();
    std::string getMessage(std::string code);

private:

    Singleton() {}; 
    Singleton(Singleton const&) = delete;
    void operator=(Singleton const&) = delete;
};
Run Code Online (Sandbox Code Playgroud)

单例.cpp

Singleton& Singleton::getInstance()
{
    static Singleton instance;
    return instance;
}


std::string Singleton::getMessage(std::string code)
{
    /// Do something
    return "Code example.";
}
Run Code Online (Sandbox Code Playgroud)

和主要代码:

主程序

int main()
{
        Singleton* my_singleton;
        my_singleton = Singleton::getInstance(); **<-- ERROR HERE**

        cout << my_singleton->getMessage("a"); << endl

}
Run Code Online (Sandbox Code Playgroud)

主要是给我一个错误: Cannot convert 'Singleton' to 'Singleton*' in assignment

“实例化”单例并使用 getMessage 函数的正确方法是什么。

非常感谢帮助...

Chr*_*lla 5

你只是像这样调用函数怎么样:

Singleton::getInstance().getMessage("a");
Run Code Online (Sandbox Code Playgroud)

而不是将其分配给变量。

  • @Mendez 不需要引用:只需将其键入:`Singleton::getInstance().getMessage("a");` 如果你想缩短它使用宏:`#define theSingleton Singleton::getInstance()` 和将它与宏一起使用:`theSingleton.getMessage("a");` (2认同)