C++-------函数重载

函数形参列表(参数个数,参数类型,参数顺序)

 


函数重载:函数名相同,参数列表不同
注意!1.函数返回值不是构成函数重载的条件。

如:int show(int,char)
   char show(int ,char) 则不构成函数重载

2.函数重载避免函数出现冲突,二义性,不要写默认参数。

如:
            int show(int a,int b);
            int show(int a,int b,int c=100);
            主函数调用:
            show(10,20);  //编译器报错,因为编译器不知道要调用哪个函数,

 

--简单的函数重载的几种情况:

1.函数参数类型相同,个数不同:
#include <iostream>
#include "stdlib.h"
using namespace std;

void show(int a,int b)
{
    cout<<"1"<<endl;
}

void show(int a,int b,int c)
{
    cout<<"2"<<endl;
}
//void show(int a,int b,int)  //占位参数依然有效,相当于函数个数依然是3个
int main()
{
    int a,b,c;
    show(10,20);           //此时输出的结果是1,即传入个数对应匹配参数个数
    system("pause");
    return 0;
}
2.函数参数个数相同,类型不同
#include <iostream>
#include "stdlib.h"
using namespace std;

void show(int a,int b,double c)
{
    cout<<"1"<<endl;
}

void show(int a,int b,int c)
{
    cout<<"2"<<endl;
}

int main()
{
    int a,b,c;
    show(10,20,1.1);         //此时输出结果为1,即传入数据类型对应参数的数据类型
    system("pause");
    return 0;
}
3.函数参数类型、个数相同,顺序不同
#include <iostream>
#include "stdlib.h"
using namespace std;

void show(int a,double b,int c)
{
    cout<<"1"<<endl;
}

void show(int a,int b,double c)
{
    cout<<"2"<<endl;
}

int main()
{
    int a,b,c;
    show(10,1,1.2);          //此时输出的是2,即调用第二个函数,传入的顺序对应参数类型的顺序
    system("pause");
    return 0;
}

 

posted @ 2019-05-22 11:22  LBC不认输  阅读(183)  评论(0编辑  收藏  举报