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

顺便编译通过!

相关推荐
m0_535064605 小时前
C++模版编程:类模版与继承
java·jvm·c++
Tanecious.6 小时前
C++--红黑树封装实现set和map
网络·c++
愚润求学8 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
源代码•宸9 小时前
C++高频知识点(十三)
开发语言·c++·经验分享·面经
lhxcc_fly10 小时前
mmap映射文件
c++·地址映射文件·!fd
有冠希没关系12 小时前
Ffmpeg滤镜
c++
闻缺陷则喜何志丹13 小时前
【并集查找 虚拟节点】P1783 海滩防御|省选-
数据结构·c++·洛谷·并集查找·虚拟节点
用户68530007547513 小时前
双指针法解决力扣922题:按奇偶排序数组II的完整指南
c++
CodeWithMe14 小时前
【读书笔记】《C++ Software Design》第十章与第十一章 The Singleton Pattern & The Last Guideline
开发语言·c++·设计模式
UP_Continue14 小时前
C++--List的模拟实现
开发语言·c++