文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。
笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888
函数模板 与 模板函数
函数模板 强调的是模板;它表示的是一个模板,专门用来生产函数,而生成的函数就是 模板函数。
格式
template<class T>
T fun(T param1, T param2)
{...}
演示实例:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
template<class T>
T fun(T param1, T param2)
{
cout << param1 << " + " << param2 << " = ";
return param1 + param2;
}
int main()
{
//整形操作
int iA = 1;
int iB = 2;
//int fun(int param1, int param2) 就是生成的模板函数
cout << fun(1, 2) << std::endl;
//字符串操作
std::string strA = "aa";
std::string strB = "bb";
//std::string fun(std::string param1, std::string param2) 就是生成的模板函数
cout << fun(strA, strB) << std::endl;
system("pause");
return 0;
}
类模板 与 模板类
类模板 强调的是模板,它表示的是一个模板,专门用于产成类,而生成的类就是 模板类。
演示实例:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
// 定义类模板
template <typename T>
class CA
{
public:
CA(T param)
{
this->m_a = param;
cout << "this->m_a = " << param << endl;
}
private:
T m_a;
};
int main()
{
int iA = 100;
CA<int> a1(iA); //使用类模板生成模板类对象
CA<char> a2('Z'); //使用类模板生成模板类对象
system("pause");
return 0;
}