This question already has answers here:
Why can templates only be implemented in the header file?
                                
                                    (16个回答)
                                
                        
                                4年前关闭。
            
                    
我的.hpp文件中有此类

template<class T = int>
class Matrix
{
    public:
    Matrix();
}


我有这个Matrix.cpp文件

#include "Matrix.hpp"
template<class T>
Matrix<T>::Matrix()
{
    vector<T> vecN(1, 0);
    _matrix.resize(1, vecN);
    _rows = 1;
    _cols = 1;
}


但添加主

#include "Matrix.hpp"

int main(int argc, char** argv)
{
    Matrix<int> test();
    return 0;
}


我得到一个很奇怪的错误说

main.cpp:19: undefined reference to Matrix<int>::Matrix(unsigned int, unsigned int)'main.cpp:19:(.text+0x2d): relocation truncated to fit: R_X86_64_PC32 against undefined symbol Matrix<int>::Matrix(unsigned int, unsigned int)

最佳答案

模板代码必须在标题中,除非是专门化的。

这是因为模板在您使用时用于生成实际的类。

09-10 01:28
查看更多