zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c++模板学习10之类模板分文件编写

C++文件模板学习 10 编写 之类
2023-09-14 09:02:34 时间

类模板分文件编写

问题:类模板中成员创建时机是在调用阶段,导致分文件编写时链接不到
解决方式1:直接包含.cpp源文件
p.h

#pragma once  //防止头文件重复包含
#include<iostream>
using namespace std;
//类模板与继承
template<class T>
class Baba
{
public:
	void fun();
};

p.cpp

#include"p.h"
//成员函数类外实现
//第二种写法
template<class T>
void Baba<T>::fun()
{
	cout << "成员函数类外实现" << endl;
}

main.cpp

#include<iostream>
using namespace std;
#include"p.cpp"
int main()
{
	Baba<int> baba;
	baba.fun();
	system("pause");
	return 0;
}

解决方式2.将.h和.cpp里面内容写到一起,然后将后缀名改为.hpp
p.hpp

#pragma once  //防止头文件重复包含
#include<iostream>
using namespace std;
//类模板与继承
template<class T>
class Baba
{
public:
	void fun();
};
//成员函数类外实现
//第二种写法
template<class T>
void Baba<T>::fun()
{
	cout << "成员函数类外实现" << endl;
}

main.cpp

#include<iostream>
using namespace std;
#include "p.hpp"
int main()
{
	Baba<int> baba;
	baba.fun();
	system("pause");
	return 0;
}

总结:主流解决方法为第二种