C ++ Singleton未定义引用 [英] C++ Singleton undefined reference to

查看:234
本文介绍了C ++ Singleton未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,试图了解C ++中的Singleton模式。

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

myclass.cpp

#include "myclass.h"

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

    return m_instance;
}

编译器无法编译。我得到以下错误,在所有3行与 m_instance

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

错误:undefined引用`Myclass :: m_instance'

error: undefined reference to `Myclass::m_instance'

推荐答案

您忘记添加:

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

正在 includemyclass.h

这篇关于C ++ Singleton未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆