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

顺便编译通过!

相关推荐
程序员龙一4 小时前
C++之static_cast关键字
开发语言·c++·static_cast
奶茶树4 小时前
【C++/STL】map和multimap的使用
开发语言·c++·stl
云知谷5 小时前
【C/C++基本功】C/C++江湖风云录:void* 的江湖传说
c语言·开发语言·c++·软件工程·团队开发
ShineWinsu6 小时前
对于数据结构:堆的超详细保姆级解析—上
数据结构·c++·算法·计算机·二叉树·顺序表·
im_AMBER7 小时前
Leetcode 46
c语言·c++·笔记·学习·算法·leetcode
QX_hao7 小时前
【Go】--文件和目录的操作
开发语言·c++·golang
卡提西亚7 小时前
C++笔记-20-对象特性
开发语言·c++·笔记
三掌柜6668 小时前
C++ 零基础入门与冒泡排序深度实现
java·开发语言·c++
沐怡旸8 小时前
【穿越Effective C++】条款15:在资源管理类中提供对原始资源的访问——封装与兼容性的平衡艺术
c++·面试
利刃大大9 小时前
【高并发服务器:HTTP应用】十五、HttpRequest请求模块 && HttpResponse响应模块设计
服务器·c++·http·项目