为什么我收到未解决的外部问题?

Why am I getting unresolved externals?

提问人:JeffreyABecker 提问时间:10/10/2009 更新时间:12/21/2010 访问量:1900

问:

我正在用 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();
C++ 模板 单例 未解析外部

评论


答:

5赞 2 revsJames McNellis #1

m_empty是静态的,因此您需要有一个源 (.cpp) 文件,如下所示:

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

注意:我最初的答案不正确,没有考虑到这是一个模板。这是安德烈T在他的回答中给出的答案;我已将此答案更新为正确答案,因为这是已接受的答案,并显示在页面顶部。请给AndreyT的答案投赞成票,而不是这个。

0赞 Moshe Levi 10/10/2009 #2

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

7赞 AnT stands with Russia 10/10/2009 #3

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

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

如有必要,还可以在此声明中提供初始值设定项(或初始值设定项)。