【发布时间】:2014-12-13 07:57:53
【问题描述】:
我在我的 C++ 程序中调用了一个模板:
const matrix::CMatrix<double> M1(3,3,{{5.0,0.0,2.0},{1.0,1.0,3.0},{6.0,7.0,7.0}});
我收到了这样的链接器错误:
tests.h:15: undefined reference to `matrix::CMatrix<double>::CMatrix(int, int, std::vector<std::vector<double, std::allocator<double> >, std::allocator<std::vector<double, std::allocator<double> > > >)'
经过大量搜索,我终于意识到这是因为我已经分离了我的 h 和 cpp 文件,而template 不能容忍它。在 C 中,建议将 c 和 h 文件分开并使用 Makefile。但是根据c++中的这些问题,是否仍然建议将cpp和h文件分开?在 h 文件中实现一些模板和在 cpp 文件中实现一些其他功能不是干净的方法。我该怎么办?
编辑:
矩阵.h
template<typename T>
class CMatrix
{
.....
矩阵.cpp
implementation of CMatrix
main.cpp
defining M1
【问题讨论】:
-
“分离”是什么意思?您的模板在哪里声明(在 .cpp 或 .h 中)以及在哪里使用?
标签: c++ templates makefile linker