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 小时前
Lambda表达式详解
数据结构·c++
leaves falling2 小时前
C++ string 类:从入门到模拟实现
开发语言·c++
样例过了就是过了3 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
liuyao_xianhui3 小时前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
cch89184 小时前
易语言与C++:编程语言终极对决
开发语言·c++
HABuo4 小时前
【linux线程(三)】生产者消费者模型(条件变量阻塞队列版本、信号量环形队列版本)详细剖析
linux·运维·服务器·c语言·c++·ubuntu·centos
小肝一下4 小时前
每日两道力扣,day2
c++·算法·leetcode·职场和发展
CheerWWW7 小时前
C++学习笔记——this关键字、对象生命周期(栈作用域)、智能指针、复制与拷贝构造函数
c++·笔记·学习
lucky九年7 小时前
GO语言模拟C++封装,继承,多态
开发语言·c++·golang
漫随流水7 小时前
c++编程:D进制的A+B(1022-PAT乙级)
数据结构·c++·算法