C++ Singleton undefined reference to

流过昼夜 提交于 2019-12-30 06:45:11

问题


I am new to C++ and trying to understand the Singleton Pattern in C++.

myclass.h

#ifndef MYCLASS_H
#define MYCLASS_H

class Myclass {
    public:
        static Myclass* getInstance();

    private:
        Myclass(){}
        Myclass(Myclass const&){}
        Myclass& operator=(Myclass const&){}
        static Myclass* m_instance;
};

#endif // MYCLASS_H

myclass.cpp

#include "myclass.h"

Myclass* Myclass::getInstance() {
    if (!m_instance) {
        m_instance = new Myclass;
    }

    return m_instance;
}

The compiler can't compile. I get the following error, on all 3 lines with m_instance:

error: undefined reference to `Myclass::m_instance'


回答1:


You forgot to add:

Myclass* Myclass::m_instance = 0; // or NULL, or nullptr in c++11

right under #include "myclass.h".



来源:https://stackoverflow.com/questions/17799134/c-singleton-undefined-reference-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!