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
解决方案
当你在一个类中声明一个静态变量时,它只是被声明了,而不是被定义了。所以你需要在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;
}