【类模板】类模板分文件编写

分文间编写容易出现的问题:
无法解析版本命令

出现的原因:
类模板成员函数出现的时间是在调用阶段

解决方法:
1.直接调用 include .cpp 文件
2.将声明和实现写在一起,改后缀名为 .hpp(约定,不是hpp也行,hpp代表类模板文件)

方法1:
main.cpp

#include<iostream>
#include<cstdio>
#include<string>
#include<typeinfo>
//#include "p.h"	// 只导入 .h 文件 会导致编译器从来没看到过 .cpp 的内容(模板类成员函数旨在确定类型后) 
#include "p.cpp"	// (直接包含源文件)因为 .cpp 其实包含了 .h
//#include "p.hpp" 	// (将声明和实现写在一起)将 .h 和 .cpp 文件写在一起,将后缀名改为 .hpp(约定,不是hpp也没事) 文件 
using namespace std;

int main()
{
	P<string,int> p = P<string,int>("ok",10);
	p.show();
	return 0;
}

p.h

#include<iostream>
#include<cstdio>
#include<string>
#include<typeinfo>
using namespace std;
template<typename T, typename R>
class P{
	public:
		T _name;
		R _age;
	public:
		P(T name, R age);
		void show();
};

p.cpp

#include<iostream>
#include<cstdio>
#include<string>
#include<typeinfo>
#include "p.h"
using namespace std;
template<typename T, typename R>
P<T,R>::P(T name, R age){
	this->_name = name;
	this->_age = age;
}

template<typename T, typename R>
void P<T,R>::show(){
	cout<<_name<<" "<<_age<<endl;
}

方法2

main.cpp

#include<iostream>
#include<cstdio>
#include<string>
#include<typeinfo>
//#include "p.h"	// 只导入 .h 文件 会导致编译器从来没看到过 .cpp 的内容(模板类成员函数旨在确定类型后) 
//#include "p.cpp"	// (直接包含源文件)因为 .cpp 其实包含了 .h
#include "p.hpp" 	// (将声明和实现写在一起)将 .h 和 .cpp 文件写在一起,将后缀名改为 .hpp(约定,不是hpp也没事) 文件 
using namespace std;

int main()
{
	P<string,int> p = P<string,int>("ok",10);
	p.show();
	return 0;
}

p.hpp

#include<iostream>
#include<cstdio>
#include<string>
#include<typeinfo>
using namespace std;
template<typename T, typename R>
class P{
	public:
		T _name;
		R _age;
	public:
		P(T name, R age);
		void show();
};

template<typename T, typename R>
P<T,R>::P(T name, R age){
	this->_name = name;
	this->_age = age;
}

template<typename T, typename R>
void P<T,R>::show(){
	cout<<_name<<" "<<_age<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值