«

3 函数提高

时间:2023-9-20 00:07     作者:wen     分类: C++


[toc]

函数提高

函数默认参数

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

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

示例:

#include <iostream>

using namespace std;

// 如果传入数据,就用自己的数据,没有,就使用默认值
int func(int a, int b = 10, int c = 20)
{
    return a + b + c;
}

// 如果函数声明有默认参数,函数实现就不能有默认参数
// 如果函数实现有默认参数,函数声明就不能有默认参数
// 函数声明和实现,只能有一个有默认参数
int funcA(int a = 10, int b);

int funcA(int a, int b)
{
    return a + b;
}

int main()
{
    int sum = func(10, 20);
    cout << sum << endl;

    system("pause");
    return 0;
}

注意:如果某个位置有默认参数,从这个位置后面的参数,都需要有默认参数

注意:函数声明和实现,只能有一个有默认参数


函数占位符

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

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

示例:

#include <iostream>

using namespace std;

//占位符
//占位参数还可以有默认参数
void func(int a, int = 10)
{
    // 目前阶段的占位符,我们还用不到,后面会用
    cout << "func" << endl;
}

int main()
{
    func(10,20);

    system("pause");
    return 0;
}


函数重载

函数重载概述

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

函数重载满足条件:

示例:

#include <iostream>

using namespace std;

void func()
{
    cout << "func 的调用" << endl;
}
// 参数不同
void func(int a)
{
    cout << "func(int a)的调用" << endl;
}
//类型不同
void func(double a)
{
    cout << "func(double a)的调用" << endl;
}
// 个数不同
void func(int a, int b)
{
    cout << "func(a,b)的调用" << endl;
}
// 随顺序不同
void func(int a, double b)
{
    cout << "func(int a,double b)的调用" << endl;
}

void func(double a, int b)
{
    cout << "func(double a,int b)的调用" << endl;
}

int main()
{
    func();
    func(10);
    func(3.14);
    func(10, 10);
    func(10, 3.14);
    func(3.14, 10);

    system("pause");
    return 0;
}


函数重载注意事项

示例:

#include <iostream>

using namespace std;

// 1.引用作用重载条件
void func(int& a) // int &a =10 不合法语法
{
    cout << "func(int& a)调用" << endl;
}

void func(const int& a) // const int& a = 10; 合法
{
    cout << "func(const int& a)调用" << endl;
}

// 2.函数重载碰到默认参数
void funcA(int a)
{
    cout << "funA(int a)的调用" << endl;
}

void funcA(int a, int b = 10)
{
    cout << "funA(int a,int b)的调用" << endl;
}

int main()
{
    int a = 10;
    func(a);
    func(10);
    // 当函数重载碰到默认参数,出现二义性,报错,尽量避免传默认参数
    //funcA(10);
    funcA(10,10);

    system("pause");
    return 0;
}

标签: C/C++ C++核心编程