创建单例类但获得未定义的引用

时间:2019-01-15 15:30:53

标签: c++

我写了个小程序,但是得到未定义的参考错误。我没有弄错我在做什么

#include <iostream>

using namespace std;
class A()
{
private:

    static A *m_object;
    A()
    {
        m_object = NULL;
    }

public:

    static A* getSingleton();

    int returnVar()
    {
        return 45;
    }

};
A* A::getSingleton()
{
    if(A::m_object == NULL)
    {
       A::m_object = new A();
    }

   return m_object;
}
int main()
{
    cout<<"Hello World";
    A *a = A::getSingleton();
    cout<<"Address of a"<<&a<<endl;
    cout<<"return a"<<a->returnVar()<<endl;
    A *b = A::getSingleton();
    cout<<"Address of a"<<&b<<endl;
    return 0;
}

错误

/home/main.o: In function `A::getSingleton()':
main.cpp:(.text+0x3): undefined reference to `A::m_object'
main.cpp:(.text+0x21): undefined reference to `A::m_object'
/home/main.o: In function `main':
main.cpp:(.text.startup+0x16): undefined reference to `A::m_object'
main.cpp:(.text.startup+0x7e): undefined reference to `A::m_object'
main.cpp:(.text.startup+0xcb): undefined reference to `A::m_object'
/home/main..o:main.cpp:(.text.startup+0xde): more undefined references to `A::m_object' follow
collect2: error: ld returned 1 exit status

1 个答案:

答案 0 :(得分:0)

当您在类内声明静态变量时,只会声明它,而未定义。因此,您需要在cpp中拥有该类的实例。

#include <iostream>

using namespace std;
class A
{
private:

    static A *m_object;
    A()
    {
        m_object = NULL;
    }

public:

    static A* getSingleton();

    int returnVar()
    {
        return 45;
    }

};
A* A::getSingleton()
{
    if(A::m_object == NULL)
    {
       A::m_object = new A();
    }

   return m_object;
}

A* A::m_object; // You forgot this line

int main()
{
    cout<<"Hello World";
    A *a = A::getSingleton();
    cout<<"Address of a"<<&a<<endl;
    cout<<"return a"<<a->returnVar()<<endl;
    A *b = A::getSingleton();
    cout<<"Address of a"<<&b<<endl;
    return 0;
}