簡體   English   中英

Singleton類中未解析的外部符號

[英]Unresolved External Symbol in Singleton Class

我已經編碼很長時間了,但是我不明白這個錯誤。 我正在編寫一個自定義系統,以為對象的特定實例提供唯一的整數ID(我稱它們為標簽)。 我正在將其中一個類作為Singleton實現。

標記系統的兩個類定義如下:

#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無法解析的外部

有誰知道為什么我會收到此錯誤?

您應該在名稱空間范圍內為靜態數據成員提供一個定義 (當前,您只有一個聲明 ):

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

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

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

如果使用的是C ++ 03,則可以將nullptr替換為NULL0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM