c++ - 类模板 cpp、hpp、cpp

标签 c++ class templates matrix

<分区>

我的 .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)

最佳答案

模板代码必须在标题中,除非它用于专门化。

这是因为模板是在你使用它的时候生成实际类的。

关于c++ - 类模板 cpp、hpp、cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32366494/

相关文章:

java - 我对 Java 的类和类型的理解正确吗?

java - 如何折叠 NetBeans 模板中的注释?

c++ - 尝试模拟 vector 时出现编译器错误 C2106

c++ - 有什么方法可以将 unique_ptr 插入到 C++0x/gcc 4.4.7 中的映射中)?

c++ - 使用 C++ 进行简单的自定义解析

php - 在 PHP 中堆叠静态类

swift - struct 中的 swift 类在分配期间是否通过副本传递?

c++ - 我们应该如何在函数中使用带有 std::accumulate 的模板来通过考虑模板而不是 "init"来返回正确的类型

c++ - 如何获取非类型模板参数的值?

c++ - 简单命令行程序中的段错误