为什么会出现无法解析的外部?
-
20-09-2019 - |
题
我在C编写的不可变的二进制搜索树++。我的终止节点由一个单空节点表示。我的编译器(的Visual C ++)似乎遇到了问题解决保存我的单保护的静态成员。我收到以下错误:
错误LNK2001:解析外部符号 “受保护:静态类boost :: shared_ptr的>节点:: m_empty”???(m_empty @ $ @节点HH @@ 1V $ @的shared_ptr V $ @节点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();
解决方案
m_empty
是静态的,所以你需要有一个源(的.cpp)的东西,如以下文件:
template <typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty;
注:我原来的答复是不正确的,并没有考虑到这是一个模板。这是AndreyT给他答案的答案;因为这是公认的答案,并显示在页面的顶部我已经更新了这个答案与正确答案。请给予好评AndreyT的答案,而不是这一个。的
其他提示
正如其他人说,你需要提供一个定义点的静态成员。然而,因为它是一个模板的成员,语法将是复杂一点的,然后发生了什么之前,建议。如果我不缺什么,它看起来应该如下:
template<typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty;
您也可以在必要时提供在此声明的初始化(初始化或)。
您需要初始化变量m_empty在.cpp文件。
不隶属于 StackOverflow