0

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

错误 LNK2001:未解析的外部符号“受保护:静态类 boost::shared_ptr > node::m_empty”(?m_empty@?$node@HH@@1V?$shared_ptr@V?$node@HH@@@boost@@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();
4

3 回答 3

7

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

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

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

于 2009-10-10T15:44:33.743 回答
5

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

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

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

于 2009-10-10T13:34:30.777 回答
0

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

于 2009-10-10T13:35:03.990 回答