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

顺便编译通过!

相关推荐
暗然而日章6 小时前
C++基础:Stanford CS106L学习笔记 4 容器(关联式容器)
c++·笔记·学习
巨人张7 小时前
C++火柴人跑酷
开发语言·c++
Gomiko9 小时前
C/C++基础(四):运算符
c语言·c++
freedom_1024_9 小时前
【c++】使用友元函数重载运算符
开发语言·c++
zmzb01039 小时前
C++课后习题训练记录Day43
开发语言·c++
赖small强10 小时前
【Linux C/C++开发】 GCC -g 调试参数深度解析与最佳实践
linux·c语言·c++·gdb·-g
CAE虚拟与现实10 小时前
C/C++中“静态链接(Static Linking)” 和 “动态链接(Dynamic Linking)释疑
开发语言·c++·dll·动态链接库·lib库
fpcc10 小时前
C++编程实践——标准库中容器存储目标分析
c++
包饭厅咸鱼11 小时前
PatchCore-----训练,测试,c++部署 工业异常检测框架
开发语言·c++·视觉检测
许长安11 小时前
C++ 多态详解:从静态多态到动态多态
开发语言·c++·经验分享·笔记