注册 登录
编程论坛 C++教室

问个C++类单实例的问题

blues1207 发布于 2010-03-18 10:17, 1344 次点击
#include <iostream>
using namespace std;
class Temp {
        public:
                static Temp * getInstance();
                static void putInstance();
        private:
                static Temp *instance;
};
Temp * Temp::getInstance()
{
        if (!instance)
                instance = new Temp();
        return instance;
}
void Temp::putInstance()
{
        if (instance) {
                delete instance;
                instance = NULL;
        }  
}
int main()
{
        Temp *p;
        p = Temp::getInstance();
        return 0;
}

=====================
上面的程序报错:
/tmp/ccpL8OB4.o: In function `Temp::putInstance()':
hello.cpp:(.text+0x79): undefined reference to `Temp::instance'
hello.cpp:(.text+0x82): undefined reference to `Temp::instance'
hello.cpp:(.text+0x90): undefined reference to `Temp::instance'
/tmp/ccpL8OB4.o: In function `Temp::getInstance()':
hello.cpp:(.text+0xa1): undefined reference to `Temp::instance'
hello.cpp:(.text+0xb6): undefined reference to `Temp::instance'
/tmp/ccpL8OB4.o:hello.cpp:(.text+0xbb): more undefined references to `Temp::instance' follow
collect2: ld returned 1 exit status

请问是什么原因啊,我不知道哪里错了,请帮助
6 回复
#2
pywepe2010-03-18 11:08
试试 调用instance里 写成  Temp::instance
#3
hahayezhe2010-03-18 11:33
if (!instance)
                instance = new Temp();
        return instance;
}
#4
mghxz2522010-03-18 11:54
新人学习,能不能请楼主用文字注明下,每一段程序的意思,谢谢。
#5
玩出来的代码2010-03-18 14:31
Temp *Temp::instance=NULL; 类外初始化。
#6
chsteven2010-03-19 12:41
{
        private:
                static Temp *instance;
};

类定义中的instance只是一个声明,对于静态成员变量,需要在类定义外单独定义并初始化该成员
Temp* Temp::instance = NULL;
#7
酷宝宝2010-03-19 13:32
楼上回答得很清楚了
1