This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
                                
                                    (32个答案)
                                
                        
                                3年前关闭。
            
                    
我正在尝试编译以下内容:

template<typename T>
class Foo {
protected:
   static Foo<T>* pool[5];
public:
   static Foo* Bar() {
      pool[1] = new Foo();
   }
};

int main() {
   Foo<int>* b = new Foo<int>();
   b->Bar();
}


我得到错误:

 undefined reference to `Foo<int>::pool'


我如何导致定义池阵列?

最佳答案

您可以像这样在类之外定义模板化类的静态成员。

// for generic T
template<typename T>
Foo<T>* Foo<T>::pool[5] = {0, 0, 0, 0, 0};

// specifically for int
template<>
Foo<int>* Foo<int>::pool[5] = {0, 0, 0, 0, 0};

09-07 23:32