C++ 函数重载

函数重载是C++实现多态性的一种方法

每个重载函数的参数类型和(或)数量必须不同;正常执行相似的操作;返回值可以不同。

#include<iostream>
int func(int x);
int func(int x,int y);
void func(double x);
using namespace std;
int main(){
    int x=10,y=20;
    double p=3.14;
    func(x);
    func(x,y);
    func(p);
    return 0;
} 
inline int func(int x){
    cout<<"In func(int),x is "<<x<<endl;
}
inline int func(int x,int y){
    cout<<"In func(int,int),x is "<<x<<", y is "<<y<<endl;
}
inline void func(double x){
    cout<<"In func(double),x is "<<x<<endl;
}

在形参和实参之间类型不能直接匹配时进行类型自动转换。

//实际返回的值只能比你定义的返回值精度低,才合法,否则不合法

//自动类型转换和函数重载实例
#include<iostream>
using namespace std;
void func(int x);
void func(short x);
void func(double x);
int main(){
    int i=1314;
    short s=520;
    double d=3.1415;
    //long l=1000; 无法通过func函数打印l的值 
    float f=1.4; //实际返回的值只能比你定义的返回值精度低,才合法,否则不合法
    func(i);
    func(s);
    func(d);
    func(f);
    return 0;
} 
void func(int x){
    cout<<"In func(int),x is "<<x<<endl;
}
void func(short x){
    cout<<"In func(short),x is "<<x<<endl;
}
void func(double x){
    cout<<"In func(double),x is "<<x<<endl;
}

以下实例中的函数func不是重载:

void func(int);
void g(){
    void func(double);  //很容易引起错误 
    //...
    func(1);  //调用func(double);
    //... 
}

但下述实例的函数func是重载:

void func(int);
void func(double);
void g(){
    //...
    func(1);  //调用func(int);
    //... 
}

 //拓:默认参数的应用之一就是函数重载的简写形式 
/* 例如:要编写strcat函数的两个版本:

void mystrcat(char *,char *,int);
void mystrcat(char *,char *);

可以使用函数重载,但用默认参数实现更简单(只要编写一个版本就可以)*/

//使用默认参数 
#include<iostream>
#include<cstring>
using namespace std;
void mystrcat(char *s1,char *s2,int len=0);
//使用默认参数统一两个版本的mystrcat 
int main(){
    char str1[]="This is a test";
    char str2[]="0123456789";
    mystrcat(str1,str2,5);
    cout<<str1<<endl;
    strcpy(str1,"This is a test"); //重置str1 
    mystrcat(str1,str2);
    cout<<str1<<endl;
    return 0;
}
void mystrcat(char *s1,char *s2,int len){
//不能写为void mystrcat(char *s1,char *s2,int len=0) 否为报告重定义错误
    while(*s1) s1++;  //等价于while(*s!='\0') s++;
                    //找到s1的末尾
    if(len==0) len=strlen(s2);
    while(*s2&&len){
        *s1++=*s2++;  //赋值后指针s1和s2再一起指向下一位 
                      //将s2接到s1末尾 
        len--; 
    }     
    *s1='\0';  //在s1末尾加上null终止符('0') 
    
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值