为什么我得到未解决的外部因素?

时间:2009-10-10 13:31:21

标签: c++ templates singleton unresolved-external

我正在用c ++编写一个不可变的二叉搜索树。我的终止节点由单个空节点表示。我的编译器(visual c ++)似乎无法解析保存我的单例的受保护静态成员。我收到以下错误:

错误LNK2001:未解析的外部符号“protected:static class boost :: shared_ptr> node :: m_empty”(?m_empty @?$ node @HH @@ 1V?$ shared_ptr @ V?$ node @ HH @@@升压@@ A)

我假设这意味着它无法解析类型节点的静态m_empty成员。它是否正确?如果是这样,我该如何解决?

代码如下:

using namespace boost;
template<typename K, typename V>
class node {
protected:
    class empty_node : public node<K,V> {
    public:
        bool is_empty(){ return true; }
        const shared_ptr<K> key() { throw cant_access_key; }
        const shared_ptr<V> value()  { throw cant_access_value; }
        const shared_ptr<node<K,V>> left()  { throw cant_access_child; }
        const shared_ptr<node<K,V>> right()  { throw cant_access_child; }
        const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value){
            return shared_ptr<node<K,V>>();
        }
        const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) { throw cant_remove; }
        const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) { return shared_ptr<node<K,V>>(this); }
    };

    static shared_ptr<node<K,V>> m_empty;
public:
    virtual bool is_empty() = 0;
    virtual const shared_ptr<K> key() = 0;
    virtual const shared_ptr<V> value() = 0;
    virtual const shared_ptr<node<K,V>> left() = 0;
    virtual const shared_ptr<node<K,V>> right() = 0;
    virtual const shared_ptr<node<K,V>> add(const shared_ptr<K> &key, const shared_ptr<V> &value) = 0;
    virtual const shared_ptr<node<K,V>> remove(const shared_ptr<K> &key) = 0;
    virtual const shared_ptr<node<K,V>> search(const shared_ptr<K> &key) = 0;


    static shared_ptr<node<K,V>> empty() {
        if(m_empty.get() == NULL){
            m_empty.reset(new empty_node());
        }
        return m_empty;
    }
};

我的树的根被初始化为:

shared_ptr<node<int,int>> root = node<int,int>::empty();

3 个答案:

答案 0 :(得分:7)

正如其他人所说,您需要为静态成员提供定义点。但是,由于它是模板的成员,因此语法将比之前建议的更复杂一些。如果我没有遗漏任何东西,它应该如下所示

template<typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty;

如有必要,您还可以在此声明中提供初始化程序(或初始化程序)。

答案 1 :(得分:5)

m_empty是静态的,因此您需要一个源(.cpp)文件,其中包含以下内容:

template <typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty;

注意:我的原始答案不正确,并没有考虑到这是一个模板。这是AndreyT在答案中给出的答案;我已使用正确答案更新了此答案,因为这是已接受的答案,并显示在页面顶部。请upvote AndreyT的回答,而不是这个。

答案 2 :(得分:0)

您需要在.cpp文件中初始化m_empty变量。