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

顺便编译通过!

相关推荐
TANGLONG2227 分钟前
【C++】继承详解——基类/派生类、作用域、默认函数、菱形继承(超详细)
java·c语言·c++·经验分享·笔记·ajax
小侯不躺平.18 分钟前
C++ Boost库【2】 --stringalgo字符串算法
linux·c++·算法
code_whiter28 分钟前
C++11(stack和queue)
开发语言·c++
用户8055336980338 分钟前
现代Qt开发教程(新手篇)2.1——QPainter 绘图基础
c++·qt
计算机安禾1 小时前
【c++面向对象编程】第12篇:继承(二):构造与析构顺序,继承中的构造函数
开发语言·c++
雪度娃娃1 小时前
结构型设计模式——享元模式
c++·设计模式·享元模式
TIEM_691 小时前
C++string|遍历、模拟实现、赋值拷贝现代写法
开发语言·c++
计算机安禾2 小时前
【c++面向对象编程】第14篇:多态(一):虚函数——实现“一个接口,多种方法”
开发语言·c++
Hua-Jay2 小时前
OpenCV联合C++/Qt 学习笔记(十七)----凸包检测、直线检测及点集拟合
c++·笔记·qt·opencv·学习·计算机视觉
basketball6162 小时前
C++ Lambda 表达式完全指南
开发语言·c++·算法