LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 708|回复: 5

这个singleton class有什么问题?

[复制链接]
发表于 2006-4-30 13:16:02 | 显示全部楼层 |阅读模式
// T.h:

class T
  {
  public:
    static T* instance();
  private:
    T() {}
    ~T() {}
    static T* smInstance;
  };

// T.cpp:


T* T::instance()
  {
  if (smInstance == NULL)
    smInstance = new T();

  return smInstance;
  }

linking的时候出现如下错误:
../T.cpp:5: undefined reference to `T::smInstance`

我用的是gcc 3.4.6 under gentoo linux,谢谢
发表于 2006-4-30 14:10:32 | 显示全部楼层
在T.cpp中再加上
T* smInstance = NULL;
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-4-30 15:25:13 | 显示全部楼层
to guyon, 我加了可是还是有错误。

我加了 T* T::smInstance = NULL;
可是编译还是出了问题:
error: `NULL' was not declared in this scope
再请问,如果我想把class的implementation和declaration都放在.h文件里,这个singleton class 的语法是什么?T* T::smInstance = NULL; 这一行应该放在什么地方?
回复 支持 反对

使用道具 举报

发表于 2006-4-30 20:01:35 | 显示全部楼层
放在实现文件中,不能都放在头文件中,否则,多次包含会有重复定义的连接错误;NULL没有声明是因为你没有包含相应头文件,比如在VC6下,你可以include <windows.h>; 如果不想引入包含,直接在头文件中加 #define NULL  (void*)0 也能凑合着用
回复 支持 反对

使用道具 举报

发表于 2006-4-30 20:41:04 | 显示全部楼层
Post by zlly20
to guyon, 我加了可是还是有错误。

我加了 T* T::smInstance = NULL;
可是编译还是出了问题:
error: `NULL' was not declared in this scope

这个,加上<stddef.h> 或<stdlib.h>试试


Post by zlly20

再请问,如果我想把class的implementation和declaration都放在.h文件里,这个singleton class 的语法是什么?T* T::smInstance = NULL; 这一行应该放在什么地方?

一般实现都放在.cpp中的了,如果想这样做,用模版咯,可以参考一下Loki库
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-4-30 22:02:43 | 显示全部楼层
谢谢, 加入了.cpp后一切正常了。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表