默认参数、占位参数、函数重载

(一)默认参数

C++函数中的形参列表中的形参是可以有默认值的

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

注意事项:

  1. 如果我们自己传入数据,就用自己的数据,如果没有,就用默认值
  2. 如果某个位置参数有默认值,那么从这个位置往后,从左往右,必须都要有默认值
  3. 如果函数声明有默认参数,函数实现就不能有默认参数,声明和实现只能有一个有默认参数
#include<iostream>
using namespace std;
 
//函数默认参数
//如果我们传入数据,则会使用我们自己的数据
//如果没有传入数据,则会使用默认值
//注意事项:从第一个默认值位置开始往后,从左到右都必须有默认值
//          如果函数声明有默认值,函数实现就不能有默认值
int test(int a,int b = 1,int c = 2)
{
    return a + b + c;
}
 
int main()
{
 
    cout << "a+b+c = " << test(10,20,30) << endl;
 
    system("pause");
    return 0;
}

输出:a+b+c = 60

(二)占位参数

C++函数中的形参列表里可以有占位参数,用来占位,调用函数时必须填补此位置

如果有了占位参数,函数调用时候必须要提供这个参数 ,但是用不到参数

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

可以声明中占位参数,而函数实现中又在占位参数后加上名称

#include<iostream>
using namespace std;
 
//占位参数
//占位参数还可以有默认值
void test(int a,int = 10)
{
    cout << "this is test" << endl;
}
 
int main()
{
    test(10,20);
 
    system("pause");
    return 0;
}

输出:this is test

c++中占位参数的意义:

1、占位参数与默认参数结合起来使用,可以做到兼容旧版本代码,提高代码的规范性

2、可以以小的改动,进行代码移植等

(三)函数重载

1.函数重载概述

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

函数重载满足条件:

  • 同一个作用域下
  • 函数名称相同
  • 函数参数 类型不同或者个数不同或者顺序不同

注意:函数返回值不可以做为函数重载的条件 即结构体前面所写的返回值类型

#include<iostream>
using namespace std;
 
//函数重载
//函数重载满足条件
// 1、同一个作用域下
// 2、函数名称相同
// 3、函数参数 类型不同或者个数不同或者顺序不同
//函数参数 
void test()
{
    cout << "test的调用" << endl;
}
 
void test(int a)
{
    cout << "test(int a)的调用" << endl;
}
 
void test(double a)
{
    cout << "test(double a)的调用" << endl;
}
 
void test(int a,double b)
{
    cout << "test(int a,double b)的调用" << endl;
}
 
int main()
{
    test();
    test(10);
    test(3.14);
    test(10, 3.14);
 
    system("pause");
    return 0;
}

输出:

test的调用
test(int a)的调用
test(double a)的调用
test(int a,double b)的调用

2.函数重载注意事项

  • 引用作为重载条件时
  • 函数重载碰到函数默认值时
#include<iostream>
using namespace std;
 
//函数重载的注意事项
//1、引用作为重载条件
void test(int &a)       //int &a = 10 不合法
{
    cout << "test的调用" << endl;
}
 
void test(const int &a) //const int & = 10 合法
{
    cout << "test(const int &a)的调用" << endl;
}
 
//2、函数重载碰到函数默认值 
void test1(int a,int b = 10)
{
    cout << "test1的调用" << endl;
}
void test1(int a)
{
    cout << "test1(int a)的调用" << endl;
}
int main()
{
    int a = 10;
    test(a);
    test(10);
    //test1(10) //当函数重载碰到默认参数,出现二义性,报错,尽量避免这种情况
    test1(10, 20);
    system("pause");
    return 0;
}

输出:

test的调用
test(const int &a)的调用
test1的调用

碰到默认参数,容易产生歧义,即传入一个数据时能运行多个函数,所以我们需要避免这种情况

 

原文链接: https://www.cnblogs.com/imreW/p/17133696.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    默认参数、占位参数、函数重载

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/318946

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月24日 下午3:06
下一篇 2023年2月24日 下午3:06

相关推荐