函数重载
函数多态(函数重载)使我们能够使用多个同名的函数。“多态”是指有多种形式。函数多态允许函数有多种形式,函数重载是指可以有多个同名的函数,对名称进行了重载。这两个术语指的是同一件事。
可以通过函数重载来设计一系列函数——它们完成相同的工作,但使用不同的参数列表。
函数重载的关键是函数的参数列表——也成为函数特征标(function signature)。C++允许定义名称相同的函数,条件是它们的特征标不同,如果参数数目或/和参数类型不同,则特征标也不同。
使用被重载的函数式,需要在函数调用中使用正确的参数。
一些看起来不同的特征标可能是不能共存的,例如:
double cube(double x);
double cube(double & x);
在调用时编译器无法确定使用那个原型。为避免这种混乱,编译器在检查函数特征标时,要把类型引用和类型本身视为同一个特征标。
匹配函数时,不区分const和非const变量。
特征标相同但函数类型不同不能重载,例如下面两个声明是互斥的:
long gronk(int n, float m);
double gronk(int n, float m);
程序8.10
#include <iostream>
unsigned long left(unsigned long num, unsigned ct);
char * left(const char * str, int n = 1);
int main()
{
using namespace std;
char * trip = "Hawaii!!";
unsigned long n = 12345678;
int i;
char * temp;
for (i = 1; i < 10; i++)
{
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete[] temp;
}
system("pause");
return 0;
}
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0)
return 0;
while (n /= 10)
digits++;
if (digits > ct)
{
ct = digits - ct;
while (ct--)
num /= 10;
return num;
}
else
return num;
}
char * left(const char * str, int n)
{
if (n < 0)
n = 0;
char * p = new char[n + 1];
int i;
for (i = 0; i < n&&str[i]; i++)
p[i] = str[i];
while (i <= n)
p[i++] = '\0';
return p;
}
不要滥用函数重载,仅当函数执行相同的任务,但是用不同形式的数据时,才应采用函数重载。