This question already has answers here:
Why can templates only be implemented in the header file?

(17个答案)


5年前关闭。




我刚刚开始学习C++编程语言,并尝试实现二进制搜索树数据结构。

当我尝试使用
g++ -c binary.cpp -o binary.o -std=c++11
g++ -c main.cpp -o main.o -std=c++11
g++ main.o binary.o -std=c++11

然后我总是会得到一些错误,说某些成员函数有一个“ undefined 的引用”
main.o: In function `BSTree<int>::insert(int const&)':
main.cpp:(.text.#some-more-text#.+0x16): undefined reference to
 `BSTree<int>::insert(BSTreeNode<int>*, int const&)'
collect2: error: ld returned 1 exit status

以下代码段仅是一个简单示例:

binary.hpp:
template<typename T>
class BSTreeNode {
public:
  T key;
  BSTreeNode<T> *left;
  BSTreeNode<T> *right;

  BSTreeNode(const T& key) : key(key), left(nullptr), right(nullptr) {};
};


template <typename T>
class BSTree {

protected:
  BSTreeNode<T> *root;

public:
  BSTree() {
    root = nullptr;
  }

  void insert(const T& key) {
    root = insert(root, key);
  }

protected:
  BSTreeNode<T>* insert(BSTreeNode<T>* node, const T& key);
};

二进制文件
#include "binary.hpp"

template<typename T>
BSTreeNode<T>* BSTree<T>::insert(BSTreeNode<T>* node, const T& key) {

  if (not node) {
    return new BSTreeNode<T>(key);
  }

  if (key < node->key) {
    node->left = insert(node->left, key);
  } else if (key > node->key) {
    node->right = insert(node->right, key);
  } else {
    throw "Key already exists!";
  }

  return node;
}

main.cpp:
#include "binary.hpp"
#include <math.h>

int main(){
  BSTree<int> bt;

  for (int i=0; i<10; i++){
    bt.insert(pow(-1, i) * i);
  }

即使经过详尽的搜索,我仍然无法弄清楚我的代码出了什么问题。

最佳答案

问题出在源文件中BSTree::insert()的模板定义之内。
简而言之,在main.ccp中对BSTree::insert()的调用中,编译器需要定义模板函数BSTree::insert(),但找不到任何内容,因为它未在 header 中定义。请记住,每个* .cpp文件都是独立编译的。

我建议您在标题中给出模板的定义,
因为您必须在每个源文件中给出一个(可能不同的)定义。

07-24 20:23