本文内容来自于对狄泰学院 唐佐林老师 C++深度解析 课程的学习总结
交换变量的方法
定义宏代码块 VS 定义函数
#include <iostream>
#include <string>
using namespace std;
/* 使用宏来完成变量交换 */
#define SWAP(t, a, b) \
do \
{ \
t c = a; \
a = b; \
b = c; \
} while (0);
/* 使用函数来完成变量交换 */
void swap(int& a, int& b)
{
int c = a;
a = b;
b = c;
}
void swap(double& a, double& b)
{
double c = a;
a = b;
b = c;
}
void swap(string& a, string& b)
{
string c = a;
a = b;
b = c;
}
int main()
{
int a = 0;
int b = 1;
SWAP(int, a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
string str1 = "str1";
string str2 = "str2";
SWAP(string, str1, str2);
cout << "str1 = " << str1 << endl;
cout << "str2 = " << str2 << endl;
double d1 = 1.0;
double d2 = 2.0;
SWAP(double, d1, d2);
cout << "d1 = " << d1 << endl;
cout << "d2 = " << d2 << endl;
cout << "---------------------------------------------------" << endl;
swap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
swap(str1, str2);
cout << "str1 = " << str1 << endl;
cout << "str2 = " << str2 << endl;
swap(d1, d2);
cout << "d1 = " << d1 << endl;
cout << "d2 = " << d2 << endl;
return 0;
}
运行结果:
实验结果:宏定义可以定义数据类型,在预处理的时候进行文本替换,但函数处理不同的数据类型时只能通过函数重载来实现。但同时宏定义也有自己的缺陷,不能进行语法检查。
宏定义代码块
优点:代码复用,适合所有的类型
缺点:编译器不知道宏的存在,缺少类型检查
定义函数
优点:真正的函数调用,编译器对类型进行检查
缺点:根据类型重复定义函数,无法代码复用
结合宏定义和函数的优缺点,C++ 引出发泛型编程的概念
泛型编程
泛型编程的概念
不考虑具体数据类型的编程方式
C++ 中泛型编程
函数模板
一种特殊的函数 可用不同类型进行调用
看起来和普通函数很相似,区别是 类型可被参数化
函数模板语法规则
template 关键字用于 声明开始进行泛型编程
typename 关键字用于 声明泛指类型
函数模板的使用
自动类型推导调用
具体类型显示调用
编程实验
#include <iostream>
#include <string>
using namespace std;
template <typename T>
void Swap(T& a, T& b)
{
T c = a;
a = b;
b = c;
}
template <typename T>
void sort(T a[], int len)
{
for(int i=0; i<len; i++)
{
for (int j=0; j<len; j++)
{
if(a[i] > a[j])
Swap(a[i], a[j]);
}
}
}
template <typename T>
void printl(T a[], int len)
{
for(int i=0; i<len; i++)
std::cout << a[i] << ",";
std::cout << std::endl;
}
int main()
{
int a[5] = {1, 4, 5,2, 3};
sort(a, 5);
printl(a, 5);
string str[6] = {"java", "c", "c++", "c#", "vb", "delphi"};
sort(str, 6);
printl(str, 6);
return 0;
}
运行结果
实验结果:利用模板库,实现了整形数组和字符串数组的排序和打印
小结
函数模板是 泛型编程 在 C++ 中的应用方式之一
函数模板能够 根据实参对参数类型进行推导
函数模板支持 显示的指定参数类型
函数模板是 C++ 中重要的代码复用方式