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);

顺便编译通过!

相关推荐
-To be number.wan4 小时前
C++ 赋值运算符重载:深拷贝 vs 浅拷贝的生死线!
前端·c++
XXYBMOOO6 小时前
内核驱动开发与用户级驱动开发:深度对比与应用场景解析
linux·c++·驱动开发·嵌入式硬件·fpga开发·硬件工程
SoveTingღ9 小时前
【问题解析】我的客户端与服务器交互无响应了?
服务器·c++·qt·tcp
温宇飞10 小时前
内存异常
c++
挖矿大亨12 小时前
C++中深拷贝与浅拷贝的原理
开发语言·c++·算法
Bruce_kaizy12 小时前
c++图论——生成树之Kruskal&Prim算法
c++·算法·图论
雾岛听蓝13 小时前
C++:模拟实现string类
开发语言·c++
XFF不秃头14 小时前
力扣刷题笔记-合并区间
c++·笔记·算法·leetcode
编程之路,妙趣横生14 小时前
STL(七) unordered_set 与 unordered_map 基本用法 + 模拟实现
c++
寂柒14 小时前
c++--
c++