本文学习自 狄泰软件学院 唐佐林老师的 C++课程
引子:
之前学习的C/C++中至少有两种交换变量的方式,分别是宏代码块和函数,但是他们有各自的缺陷,宏由于是在预处理阶段替换的,所以编译器不知道宏的存在,缺少类型检查。而定义函数的话,虽然编译器可以进行类型检查,但是却需要根据类型重复定义函数,无法代码复用。由此,C++ 推出了 泛型编程的概念(函数模板,类模板),不考虑具体数据类型的编程方式。
实验1: 宏代码块 和 函数 来替换变脸的缺陷
实验2: 函数模板


实验1:变量交换的两种方法:宏 VS 函数
#include <iostream>
#include <string>
using namespace std;
//t 为 a,b 的类型
#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(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
double m = 2;
double n = 3;
Swap(m, n);
cout << "m = " << m << endl;
cout << "n = " << n << endl;
string d = "Delphi";
string t = "Tang";
Swap(d, t);
cout << "d = " << d << endl;
cout << "t = " << t << endl;
return 0;
}






实验2:函数模板使用
#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=i; j<len; j++)
{
if( a[i] > a[j] )
{
Swap(a[i], a[j]);
}
}
}
}
template < typename T >
void Println(T a[], int len)
{
for(int i=0; i<len; i++)
{
cout << a[i] << ", ";
}
cout << endl;
}
int main()
{
int a[5] = {5, 3, 2, 4, 1};
Println(a, 5);
Sort(a, 5);
Println(a, 5);
string s[5] = {"Java", "C++", "Pascal", "Ruby", "Basic"};
Println(s, 5);
Sort(s, 5);
Println(s, 5);
return 0;
}

本文探讨了C/C++中变量交换的多种方法及其局限性,对比宏代码块与函数的优缺点,并引入C++函数模板和类模板,实现代码复用与泛型编程,通过实例演示了不同数据类型下的变量交换和排序。
705

被折叠的 条评论
为什么被折叠?



