c++ - 编译头文件定义了一个模板类,其中还包括其他头文件

标签 c++ templates hyperlink g++

<分区>

只是说清楚:这与我们必须在头文件中定义模板类的函数的问题不同

更新 :如果您需要真正的源代码,可以在这里下载:https://Near@bitbucket.org/Near/compile_error.git

我实现了一个双列表类。

// list.h //
class list {
  //...
  void insert(...);
};

// list.cpp //
#include "list.h"
void list::insert(...) {
  ...
}

我还实现了一个包含 list.h 的模板类

// template_class.h //
#include "list.h"
template<class T>
class temp_class {
  list l;
  void func();
}

void temp_class::func() {
  //...
  l.insert(...);
}

现在我编写了一个包含 template_class.h 的 test.cpp 文件并调用了 func 函数

// test.cpp //
#include "template_class.h"
int main() {
  temp_class<int> t;
  t.func();
  return 0;
}

我是这样编译的

g++ test.cpp list.cpp -o test

编译器提示 test.cpp:“未定义的插入引用”。 为什么它不能工作?如何解决这个错误?


仅供引用:如果我将 list.cpp 中的内容包含在 list.h 中并只编译 test.cpp,它就可以工作。但我认为这不是一个好主意。

最佳答案

编译您的代码时,我立即收到警告:

list_double.h:14:15: warning: inline function ‘void list_double_node::list_double_insert_first(list_double_node*)’ used but never defined [enabled by default]
void inline list_double_insert_first(list_double_node* entry);

也就是说,您的代码实际上类似于 SSCCE :

// list.h
class list {
public:
  inline void insert(int);
};

.

// list.cpp
#include "list.h"
void list::insert(int) {
}

.

// template_class.h
#include "list.h"
template<class T>
class temp_class {
  list l;
public:
  void func();
};
template <class T>
void temp_class<T>::func() {
  l.insert(17);
}

.

// test.cpp
#include "template_class.h"
int main() {
  temp_class<int> t;
  t.func();
  return 0;
}

修复方法是:删除 inline 或在 header 中定义函数。 inline 的规则实际上与模板的规则几乎相同:无论何时使用 inline 函数,都必须提供其实现。

关于c++ - 编译头文件定义了一个模板类,其中还包括其他头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20339101/

相关文章:

c++ - 关于虚函数模板化的问题

html - 使用 href 的 CSS 标签

c++ - 构建模板类型的编译时列表?

c++ - Qpushbutton 上的圆形图标

c++ - decltype 在不生成代码的模板方法上抛出错误

c++ - 如何正确公开基础模板类型以用作类型

c++ - 输出后无法去除随机数

c++ - 在 union 中存储 STL 迭代器是否合法?

javascript - 带有 onclick 的 href 在 Safari 中不起作用

vba - 在 Excel 中将批量文本转换为超链接