1.函数重载
函数重载让您能够使用多个同名的函数。函数重载的关键是函数的参数列表也叫函数的特征标,如果两个函数的参数数目和类型相同,同时参数的排序也相同则他们的特征标相同,与变量名没关系。
比如这两个print函数
void print(const char*str,int width);
void print(const char*stl,int length);
这是一个函数表达的一个意思。类型都是char 和int 前面加了一个const (只读);
函数重载表示特征标不同,函数名就可以设置成一样。比如
void print(const char*str,int width); #1
void print(double d,int width); #2
这两个函数中函数名没变都是print但是参数类型变了,那么么如何调用呢?
与其参数类型有关如果你输入一个char型和int型自动带入#1函数比如
print("package",12);
输入double型和int型带入#2函数
当然含有若含有地址符&
double cube(double x);
double cube (double &x);
编译器会识别为一种函数,当你调用时,编译器会无法选择出现错误。
2.函数模板
函数模板是一种通用的函数描述。可以使用泛型定义函数(不必是具体类型,可以根据不同需要赋予他类型)。下面介绍个例子
template <typename anytype>
void Swap(anytype &a,anytype &b)
{
anytype temp;
temp = a;
a = b;
b = temp;
}
template typename 是关键字建立模板时需要输入的信息。 anytype 类型名称自定。你输入参数为int型变量就变为int型,输入参数为double就是double,这意味着许多相似的算法如果只是参数类型不同,可以用同一个模板。
同样我们也可以重载模板。
比如
template <typename anytype>
void Swap(anytype &a,anytype &b)
{
anytype temp;
temp = a;
a = b;
b = temp;
}
template <typename anytype>
void Swap(anytype a[],anytype b[], int n)
{
anytype temp;
for (int i = 0; i < n; i++)
{
temp = a;
a = b;
b = temp;
}
}
第二个Swap函数加入int n 依然可以设成同一个函数名进行调用;
但是模板有些局限性,比如对于数组和结构类型数据可能无法进行运算。
3.练习
编写一个模板函数max(5),他将一个包含5个T类型元素的数组作为参数,并返回数组中最大的元素(由于长度固定,因此可以在循环中使用硬编码,而不必通过参数传递)。在一个程序中使用该函数,将T替换为包含五个int值得数组和6个包含double值的数组以测试该函数。
#include <iostream>
template <typename T>
void Swap(T a[],int n);
int main()
{
using namespace std;
int things[5] = {12,20,30,10,340};
double thingc[5] = {12.1,13.9,14.9,15.8,15.1};
Swap(things,5);
Swap(thingc,5);
return 0;
}
template <typename T>
void Swap(T a[],int n)
{
using namespace std;
T temp;
temp = a[0];
for (int i = 0;i < n;i++)
if (a[i] > temp)
temp = a[i];
cout<<temp<<' ';
}
运行正确