1

我在类的层次结构下面定义了,我的目的是设计一个通用类,允许我迭代枚举对象(不幸的是,不允许使用 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

"

谁能建议我在上面的代码中缺少什么?

谢谢!

4

3 回答 3

1

静态数据成员在类定义中声明并在类定义之外定义。像这样:

// header:
class C {
    static int i;
};

// source:
int C::i = 17;

使用模板,您通常不会将任何代码放入源文件中,因此定义位于标题中:

// header:
template <class T>
class C {
    static int i;
};

template <class T>
int C<T>::i = 17;
于 2013-04-04T12:45:25.497 回答
0

你只能写

// template<> -> you should not write this in this case.
Base<Derived>::instances Base<Derived>::s_instances;

如果您提供了 的明确专业化Base<Derived>,例如:

class Derived;
template <>
class Base<Derived>
{
protected:
  explicit Base(int value);
  typedef typename std::set< Base<Derived>* > instances;
  static instances s_instances;
  int value_;


public:
  int get_value() const { return value_ ; }
};

否则,你必须坚持写作:

template<typename T>
typename Base<T>::instances Base<T>::s_instances;
于 2013-04-04T05:05:54.620 回答
0

请注意,s_instances 在使用之前可能尚未初始化。

于 2013-04-04T05:22:32.393 回答