类模板份文件编写

问题:

类模板中成员函数创建时机是在调用阶段,导致份文件编写时链接不到

解决方法:

1.直接包含cpp源文件(不常用)
2.将声明和实现写到同一个文件中,并更改后缀名为.hpp,hpp是约定名称,并不是强制。

 

.hpp中的内容 

 

#pragma once
#include<iostream> 
using namespace std;
#include<string>

//类模板成员函数类外实现 
template<class T1,class T2> 
class Person
{
public:
	//类内声明
	Person(T1 name,T2 age);
	void ShowPerson(); 
public:
	T1 m_Name;
	T2 m_Age;	
};

//构造函数 
template<class T1,class T2>
Person<T1,T2>::Person(T1 name,T2 age)
{
	this->m_Name=name;
	this->m_Age=age;
}

//成员函数 
template <class T1,class T2>
void Person<T1,T2>::ShowPerson()
{
	cout<<"姓名:"<<this->m_Name<<"\t"<<"年龄:"<<this->m_Age<<endl;
}

主函数内容: 

#include "p180.hpp"
void test01()
{
	Person<string,int>p("唐昊",50);
	p.ShowPerson();
}

int main()
{
	test01();
	
	system("pause");
	return 0;
}

 

 

 

  • 10
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你想要将模板函数的实现与声明分离到不同的文件中时,可以使用模板的显式实例化来实现模板函数的分文件编写。下面是一个示例,演示如何使用模板将选择排序算法的实现和声明分离到不同的文件中: 在`selectionsort.h`头文件中,声明选择排序算法的模板函数: ```cpp #ifndef SELECTIONSORT_H #define SELECTIONSORT_H #include <vector> template<typename T> void selectionSort(std::vector<T>& arr); #include "selectionsort.cpp" // 包含模板函数的实现 #endif ``` 在`selectionsort.cpp`源文件中,实现选择排序算法的模板函数: ```cpp #include "selectionsort.h" template<typename T> void selectionSort(std::vector<T>& arr) { int n = arr.size(); for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } std::swap(arr[i], arr[minIndex]); } } // 显式实例化模板函数 template void selectionSort<int>(std::vector<int>& arr); template void selectionSort<double>(std::vector<double>& arr); // 可以根据需要添加其他类型的实例化 ``` 在主程序文件`main.cpp`中,使用选择排序算法进行排序: ```cpp #include <iostream> #include <vector> #include "selectionsort.h" int main() { std::vector<int> nums = {5, 2, 8, 9, 1}; selectionSort(nums); std::cout << "排序结果: "; for (const auto& num : nums) { std::cout << num << " "; } std::cout << std::endl; return 0; } ``` 在上面的示例中,`selectionsort.h`头文件中声明了选择排序算法的模板函数,并包含了`selectionsort.cpp`源文件,其中包含了模板函数的实现。 在`selectionsort.cpp`源文件中,我们使用了显式实例化来实例化选择排序算法的模板函数,以便在链接时能够生成对应类型的函数定义。这里示范了对`int`和`double`类型的实例化,你可以根据需要添加其他类型的实例化。 在主程序文件`main.cpp`中,我们包含了`selectionsort.h`头文件,并使用选择排序算法对向量进行排序。 请注意,在使用分文件编写模板时,需要将模板函数的实现放在`selectionsort.cpp`源文件中,并在需要使用模板函数的地方进行显式实例化。这样,在编译和链接时,编译器可以找到模板函数的实现并生成对应类型的函数定义。 希望这个示例能满足你的需求!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值