我在类的层次结构下面定义了,我的目的是设计一个通用类,允许我迭代枚举对象(不幸的是,不允许使用 C++11)。类定义和测试程序是:
// base.h
#include <set>
template <typename T>
class Base
{
protected:
explicit Base(int value);
typedef typename std::set< Base<T>* > instances;
static instances s_instances;
int value_;
public:
int get_value() const { return value_ ; }
};
template <typename T>
Base<T>::Base(int value): value_(value)
{
s_instances.insert(this);
}
//派生的.h
#include "base.h"
class Derived : public Base<Derived>
{
protected:
explicit Derived(int value): Base<Derived>(value) { }
public:
static const Derived value1;
};
// 测试.cc
#include "derived.h"
template<>
Base<Derived>::instances Base<Derived>::s_instances;
const Derived Derived::value1(1);
int main(int argc, char *argv[])
{
using std::cout;
using std::endl;
cout << Derived::value1.get_value() << endl;
}
在使用 g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 编译时,它给了我以下链接错误:“
g++ test.cc -o test
/tmp/ccOdkcya.o: In function `Base<Derived>::Base(int)':
test.cc:(.text._ZN4BaseI7DerivedEC2Ei[_ZN4BaseI7DerivedEC5Ei]+0x28): undefined reference to `Base<Derived>::s_instances'
collect2: ld returned 1 exit status
"
谁能建议我在上面的代码中缺少什么?
谢谢!