初级玩家

- 贡献度
- 0
- 金元
- 516
- 积分
- 52
- 精华
- 0
- 注册时间
- 2021-6-13
|
#include <iostream>
#include "tt.h"
#include "diaoyong.h"
using namespace std;
template <typename T> // template <class T> 类和函数都能写成class
void lzzTemSwap(T &a, T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
template <typename T>
T lzzAdd(T a, T b)
{
return a + b;
}
template <class T>
void fooTemp()
{
cout << "This is fooTemp" << endl;
}
/* 模板定义,及建议使用手动指定类型
*/
void test_Create()
{
int aa = 5;
int bb = 44535;
char cc = 'c'; // c=97
// 自动推导类型
lzzTemSwap(aa, bb);
// lzzTemSwap(aa, cc);// 错误,自动推导出的类型不一致
cout << "aa = " << aa << endl;
cout << "ab = " << bb << endl;
// 手动指定类型
lzzTemSwap<int>(aa, bb);
cout << "aa = " << aa << endl;
cout << "ab = " << bb << endl;
// 模板必须确定出类型才能使用
fooTemp<int>();
// fooTemp();// 错误,无法推导出类型
}
/* 普通函数会自动【隐式类型转换】
模板自动推导不能自动转换类型,必须指定类型
*/
void template_main()
{
cout << "Hello template_main=============================================" << endl;
// 一、函数模板
test_Create();
test_yinshizuanhuan();
// 普通函数与模板函数的调用规则
test_diaoyong();
// 二、类模板
}
|
|