c++单例类编译不通过
阿神
阿神 2017-04-17 13:34:10
0
2
835
class Singleton
{
private:
    static Singleton* m_instance;
    Singleton() {}
public:
    static Singleton* getInstance();
};

Singleton* Singleton::getInstance()
{
    if (m_instance==nullptr)
    {
        if (m_instance==nullptr)
        {
            m_instance = new Singleton;
        }
    }
    return m_instance;
}


vs报错:
严重性    代码    说明    项目    文件    行    禁止显示状态

错误 LNK2001 无法解析的外部符号 "private: static class Singleton * Singleton::m_instance" (?m_instance@Singleton@@0PAV1@A) billapp C:\Users\Administrator\Documents\Visual Studio 2015\Projects\billapp\billapp\bill.obj 1
严重性 代码 说明 项目 文件 行 禁止显示状态
错误 LNK2019 无法解析的外部符号 _main,该符号在函数 "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) 中被引用 billapp C:\Users\Administrator\Documents\Visual Studio 2015\Projects\billapp\billapp\MSVCRTD.lib(exe_main.obj) 1


为什么会不通过?
阿神
阿神

闭关修行中......

Antworte allen(2)
大家讲道理

需要在类声明外加上一句
Singleton * Singleton::m_instance = 0;
否则会有链接错误

阿神

错误可能跟静态成员的声明有关。

另外,单例模式可以使用局部静态变量的引用实现。参考这里。

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Dont forget to declare these two. You want to make sure they
        // are unacceptable otherwise you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!