3. 函数重载

3.1  函数默认值

在c++中,函数的形参列表是可以有默认值的。

语法:返回值类型  函数名 (参数 = 默认值){ }

#include <iostream>
using namespace std;
//函数的默认参数

//如果我们自己传入数据,就用自己的数据;如果没有,就用默认值
int func ( int a,int b,int c);
int func( int a ,int b=20 ,int c=30 )
{
    return a+b+c;
}
int main()
{
    cout << func(10) <<endl ; //结果为60
    cout << func(10,30) <<endl; //结果为70
    system ("pause");
    return 0;
}

注意事项:

  • 如果某个位置已经有了默认参数,那么从这个位置往后,从左至右必须有默认值
  • 如果函数声明有默认参数,函数实现就不能有默认参数-----声明和实现只能有一个有默认参数

 

3.2  函数占位参数

c++中函数的参数列表可以有占位参数,用来做占位,调用函数时必须填补该位置

语法:返回值该类型  函数名(数据类型){ }

void func(int a,int )
{
    cout << "this is func" <<endl;
}
//目前阶段的展位参数,我们还用不到,后面课程中用到
//占位参数,还可以有默认参数
//主函数调用时,展位参数必须填补

3.3 函数重载

  作用:函数名可以相同,提高复用性。

函数重载满足的条件:

  • 同一个作用域下

  • 函数名称相同

  • 函数参数(形参列表里面的)类型不同或者个数不同或者顺序不同

注意:函数的返回值不可以作为函数重载的条件

#include <iostream>
using namespace std;

//函数重载:可以函数名相同,提高复用性
//函数参数顺序不同,类型不同,个数不同

void func()
{
    cout<<"hello" <<endl;
}
void func(int a)
{
    cout<<"hello word" <<endl;
}
int main()
{
    func();
    func(10);
    system ("pause");
    return 0;
}

3.3.2  函数重载的注意事项

  • 引用作为函数重载条件

  • 函数重载碰到函数的默认参数(可能会报错)

#include <iostream>
using namespace std;

//1.引用作为重载的条件
void fun(int &a)  //int &a=10;不合法
{
    cout << "fun(int &a)调用" <<endl;
}
void fun(const int &a) //const 限制只能读 { cout << "fun(const int &a)调用" <<endl; } //2.函数重载碰到默认参数 void fun2(int a) { cout<<"fun2(int a)" <<endl; } void fun2(int a,int b=10) { cout<<"fun2(int a,int b=10)" <<endl; } int main() { int a=10; fun (a); //调用void fun(int &a)函数 fun(10);//调用void fun(const int &a)函数; // fun2(10); 当函数重载碰到默认参数,出现二义性,报错,尽量避免这种情况 system("pause"); return 0; }
哪有什么胜利可言,坚持意味着一切
原文地址:https://www.cnblogs.com/BY1314/p/12747046.html