函数的重载

函数的默认参数可以令我们使用具有不同参数数目的同一个函数,而函数多态可以令我们使用多个相同名称的函数。多态指的是多种形式,函数多态允许函数具有多种形式。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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值