函数的默认参数可以令我们使用具有不同参数数目的同一个函数,而函数多态可以令我们使用多个相同名称的函数。多态指的是多种形式,函数多态允许函数具有多种形式。c++使用上下文来确定使用的重载函数版本。
函数重载
1. c++允许定义名称相同的函数,前提是他们的特征标不同,即参数数目或参数类型不同。 例如,定义一组原型如下的函数:
void print(const char * str , int width);
void print(double d , int width);
void print(long l , int width);
void print(int i , int width);
void print(const char * str);
2. 使用被重载的函数时,需要在函数调用中使用正确的参数类型。例如,下面的语句:
unsigned int year=3210;
print(year,6);
调用时,没有与print函数匹配的函数原型,但是c++将会尝试使用强制类型转换强制进行匹配。但是上述print函数有三个可以强制转换的目标函数,所以c++将拒绝这种函数调用,视为错误。
3. 一些看起来形式不同,但是实质相同的特征标也是不能共存的。 例如,下面的代码:
double cube(doube x);
double cube(double & y);
编译器在检查函数特征标时,将类型引用和类型本身视为同一个特征标。
4. 是特征标,而不是函数返回值类型使得可以对函数进行重载。
比如,下面的语句:
long cube(doube x);
double cube(double x); //invalid
c++不允许此种情况出现,函数返回类型可以不同,但是特征标必须不同。
实例:
// leftover.cpp -- overloading the left() function
#include <iostream>
unsigned long left(unsigned long num, unsigned ct);
char* left(const char* str, int n = 1);
int main()
{
using namespace std;
char array[9] = "Hawaii!!";
char* trip = array; // test value
unsigned long n = 12345678; // test value
int i;
char* temp;
for (i = 1; i < 10; i++)
{
cout << left(n, i) << endl;
temp = left(trip, i);
cout << temp << endl;
delete[] temp; // point to temporary storage
}
// cin.get();
return 0;
}
// This function returns the first ct digits of the number num.
unsigned long left(unsigned long num, unsigned ct)
{
unsigned digits = 1;
unsigned long n = num;
if (ct == 0 || num == 0)
return 0; // return 0 if no digits
while (n /= 10)
digits++;
if (digits > ct)
{
ct = digits - ct;
while (ct--)
num /= 10;
return num; // return left ct digits
}
else // if ct >= number of digits
return num; // return the whole number
}
// This function returns a pointer to a new string
// consisting of the first n characters in the str string.
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]; // copy characters
while (i <= n)
p[i++] = '\0'; // set rest of string to '\0'
return p;
}