1

我已经编码很长时间了,但我不明白这个错误。我正在编写一个自定义系统,用于为对象的特定实例提供唯一的整数 ID(我称它们为标签)。我正在将其中一个类实现为单例。

标记系统的两个类定义如下:

#include "singleton.h"

class Tag: public bear::Singleton<Tag>
{
public:
    static dUINT32 RequestTag(Tagged* requester);
    static void RevokeTags(void);
private:
    Tag(void);
    ~Tag(void);

    Tagged** m_tagTable; // list of all objects with active tags
    dUINT32  m_tagTable_capacity, // the maximum capacity of the tag table
             m_tagIndexer; // last given tag
};

class Tagged
{
    friend class Tag;
public:
    inline dUINT32 GetTag(void) {return m_tag;}
private:
    inline void InvalidateTag(void) {m_tag=INVALID_TAG;}
    dUINT32 m_tag;
protected:
    Tagged();
    virtual ~Tagged();
};

Singleton 类的定义如下:

template <typename T>
class Singleton
{
public:
    Singleton(void);
    virtual ~Singleton(void);

    inline static T& GetInstance(void) {return (*m_SingletonInstance);}
private:
    // copy constructor not implemented on purpose
    // this prevents copying operations any attempt to copy will yield
    // a compile time error
    Singleton(const Singleton<T>& copyfrom);
protected:
    static T* m_SingletonInstance;
};

template <typename T>
Singleton<T>::Singleton (void)
{
    ASSERT(!m_SingletonInstance);
    m_SingletonInstance=static_cast<T*>(this);
}

template <typename T>
Singleton<T>::~Singleton (void)
{
    if (m_SingletonInstance)
        m_SingletonInstance= 0;
}

尝试编译文件并将文件链接在一起时出现以下错误:

test.obj:错误 LNK2001:未解析的外部符号“受保护:静态类 util::Tag * Bear::Singleton::m_SingletonInstance”(?m_SingletonInstance@?$Singleton@VTag@util@@@bear@@1PAVTag@util@@ A) 1>C:...\tools\Debug\util.exe : 致命错误 LNK1120: 1 unresolved externals

有谁知道我为什么会收到这个错误?

4

1 回答 1

2

您应该在命名空间范围内为您的静态数据成员提供定义(目前,您只有一个声明):

template <typename T>
class Singleton
{
    // ...

protected:
    static T* m_SingletonInstance; // <== DECLARATION
};

template<typename T>
T* Singleton<T>::m_SingletonInstance = nullptr; // <== DEFINITION

如果您使用的是 C++03,则可以替换nullptrNULL0

于 2013-05-15T00:25:09.830 回答