带有模板编译错误的 C++ 类

标签 c++ class templates linker

我不是经验丰富的 C++ 程序员,而且我在编译时遇到了问题。我有一个使用模板的堆类:

template <class T>
class Heap
{
  public:
    Heap(const vector<T>& values);

  private:
    vector<T> d;

  // etc.
};

然后在单独的实现文件中:

template <class T>
Heap<T>::Heap(const vector<T>& values)
{
d = values;

for (unsigned int i = d.size()-1; i > 0; i--) Heapify(ParentIndex(i));
}

// ... more implementation code ...

最后是一个 main.cc 文件:

int main (int argc, char *argv[])
{
  vector<int> in;
  unsigned int i;

  while (cin >> i) in.push_back(i);
  Heap<int> h = Heap<int>(in);

  return 0;
} 

我得到这些编译错误:

g++ -Wall -I/opt/local/include -c -o main.o main.cc
g++ -Wall -I/opt/local/include -c -o heap.o heap.cc
g++ -Wall -o heap main.o heap.o
Undefined symbols:
  "Heap<int>::Heap(std::vector<int, std::allocator<int> > const&)", referenced from:
      _main in main.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [heap] Error 1

为什么不能编译?我认为链接器说它找不到构造函数,但我知道它生成了目标文件。

最佳答案

模板需要 100% 在头文件中定义。如果您有 Heap<T>在 .cc/.cpp 文件中实现就是问题所在。将所有代码移至头文件,它应该可以解决您的问题。

关于带有模板编译错误的 C++ 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1631398/

相关文章:

c++ - C++ 模板函数的行为

c++ - 为单参数模板调用的特定值调用具有更多参数的调用模板特化

c++ - 在自定义类 vector 中查找

c++ - 使用具有继承类值的基类函数

c++ - 如何在构造函数中将基类实例化为派生类?

PHP - 将类常量值分配给构造函数中的属性

class - UML 类图 - 来自其他类的方法 - 哪个连接器?

c++ - 无法将 PFX 导入 Microsoft 示例 key 存储提供程序(加密提供程序开发工具包)

c++ - 在什么情况下调用常量取消引用运算符?

C++ 运算符错误