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

顺便编译通过!

相关推荐
我不会插花弄玉2 小时前
15.map,set下:AVL树,红黑树和map,set的封装【由浅入深-C++】
c++·stl
hold?fish:palm2 小时前
20 旋转图像
c++·算法·leetcode
此生决int3 小时前
深入理解C++系列(10)——lsit
开发语言·c++
NoteStream3 小时前
【C语言基础】分支和循环(上)
c语言·开发语言·c++·经验分享·笔记·算法·c#
2401_827499993 小时前
C++(黑马)05-提高编程
java·开发语言·c++
hold?fish:palm4 小时前
链表的基本原理和实现(C++版本)
数据结构·c++·链表
jufeng13074 小时前
【系列:MiniKV 原理剖析 · 第 5 篇】
linux·网络·c++·软件工程
豆沙沙包?4 小时前
C++-程序的内存模型(P84-P88)
java·jvm·c++
jufeng13074 小时前
【系列:MiniKV 原理剖析 · 第 8 篇(完结篇)】
linux·c++·log4j·软件工程·makefile
VL——MOESR5 小时前
【LuoguP1967】货车运输【生成树】【倍增】
c++·算法·题解·倍增·生成树