0

我正在使用模板和静态成员实现一些想法。尽管“真实”代码会产生另一个错误,但这是我在玩具示例代码中仍然存在的错误

#include <string>
#include <iostream>

template<int dim>
class Class1 {
  public:
     Class1() {};
    ~Class1() {};
     void foo() {
        std::cout<<"foo-1"<<std::endl;
     }
   protected:
     std::string name;
};

template<int dim>
class Class2 : public Class1<dim>
{
  public:
     Class2(const int & a, const int &b) : 
        number( Class2<dim>::id_generator++ ) 
     {
        Class1<dim>::name = "My-name"; 
        foo(); // (1)
      };

 void foo() {
    Class1<dim>::foo();
    std::cout<<"foo-2"<<std::endl;
 }

 private:
    const unsigned int number;
    static unsigned int id_generator;
};

 int main() 
 {
    int a = 1, b=2;
    Class2<2> class2(a,b);   // (2)
 }

与链接器错误:

 undefined reference to `Class2<2>::id_generator' 

现实生活中的例子产生2个错误

 (1) required from 'Class2<dim>::Class2(int, int) [with int dim = 3]'
 (2) required from here.

现实生活中的错误完全没有告诉我!:(我希望如果玩具问题得到解决,现实生活中的问题也会消失,但如果有人对结构上下文中的“现实生活”错误(这两行)有任何想法,请,让我知道。

4

2 回答 2

1

您忘记为您的static数据成员添加定义id_generator。在全局命名空间级别添加:

template<int dim>
unsigned int Class2<dim>::id_generator = 0;

With this addition, you can see your code correctly compiling and linking here.

于 2013-03-30T14:03:19.370 回答
1

Well, as the error message says, there is no definition of the static data member. If this was an ordinary class, you'd put the definition in a source file:

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

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

A template is a pattern; the compiler uses it to generate code. So what you want to end up with when the compiler instantiates the template is something like the preceding code. But template code goes in headers, not source files, so you write it like this:

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

template <class T>
int C<T>::i = 3;
于 2013-03-30T14:05:32.600 回答