C++ 模板的编译链接讨论

//头文件

#ifndef Test_h__

#define Test_h__

template<class T>

class Test1

{

public:

static T Add(const T& x, const T& y);

};

#endif // Test_h__

//cpp文件

#include "Test.h"

template<class T>

T Test1<T>::Add(const T& x, const T& y)

{

return x + y;

}

//使用地方

Test1<int>::Add(1, 2);

以上编译会出现,链接问题,原因是,类模板必须显示初始化,也就是告诉具体类型

解决办法:

//修改后的cpp文件

#include "Test.h"

template<class T>

T Test1<T>::Add(const T& x, const T& y)

{

return x + y;

}

//要声明一次

template

int Test1<int>::Add(const int& x, const int& y);

顺便编译通过!

相关推荐
郑同学的笔记5 小时前
【c++随笔28】strcmp 和 memcmp对比
开发语言·c++
随意起个昵称6 小时前
【背包dp】输出方案路径
c++·动态规划
朝朝辞暮i6 小时前
C++ 第 27 课:智能指针 shared_ptr
开发语言·c++·算法
by209997 小时前
学会使用std::string类,并理解其内部是如何管理字符串的详细阐述(上)
c++·笔记·字符串·类和对象·string
沙漠之主7 小时前
C++编程教学设计资料:从入门到实战的完整课程方案
java·前端·c++
朝朝辞暮i7 小时前
C++ 第 29 课:回调函数 Callback
开发语言·c++·算法
kaixin_learn_qt_ing7 小时前
C++多态实现原理
c++
无名猿8 小时前
unique_ptr 完全指南:独占所有权与零开销
c++·性能优化·内存管理·标准库·现代c++
笑鸿的学习笔记8 小时前
C++笔记之大块顺序写
java·c++·笔记
无名猿9 小时前
对象构造与析构顺序全解:声明顺序、继承链与逆序析构
c++·内存管理·调试技巧·现代c++