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

顺便编译通过!

相关推荐
旖旎夜光27 分钟前
多态(11)(下)
c++·学习
yangpipi-36 分钟前
《C++并发编程实战》 第4章 并发操作的同步
开发语言·c++
Chance_to_win1 小时前
C++基础知识
c++
有趣的我1 小时前
C++ 多态介绍
开发语言·c++
WBluuue2 小时前
Codeforces 1068 Div2(ABCD)
c++·算法
阿沁QWQ2 小时前
C++的map和set
开发语言·c++
charlie1145141914 小时前
现代C++工程实践:简单的IniParser3——改进我们的split
开发语言·c++·笔记·学习
fish_xk4 小时前
c++的引用和类的初见
开发语言·c++
晨尘光5 小时前
【Windows 下FlatBuffers 编译.fbs文件并应用】
c++·windows
煤球王子6 小时前
学而时习之:C++中的文件处理2
c++