黑马程序员C++核心编程笔记--3 函数高级

3.1 函数默认参数

本节内容之前已经整理过,详见22.函数的默认值

3.2 函数占位参数

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

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

在现阶段函数的占位参数存在意义不大,但是后面的课程中会用到该技术

示例:

cpp 复制代码
#include <iostream>
using namespace std;


// 函数占位参数,占位参数也可以有默认值
void func(int a, int) {
    cout  << "this is a func" << endl;
}

int main() {
    func(1, 2);
    return 0;
}

3.3 函数重载-基本语法

作用 :函数名可以相同,提高复用性
函数重载满足条件

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

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

示例:

cpp 复制代码
#include <iostream>
#include <iostream>
using namespace std;

// 1.参数类型不同
void print(int a)
{
    cout << "int" << endl;
}
void print(double a)
{
    cout << "double" << endl;
}

// 2.参数顺序不同
void print(double a, int b) {
    cout << "int int" << endl;
}
void print(int a, double b) {
    cout << "double double" << endl;
}
// 注意:同类型参数顺序不同是不被允许的,因为函数名相同,编译器会认为这是同一个函数
// void print(int a, int b) {}和void print(int b, int a) {}同时出现时,编译器会报错

// 3。参数个数不同
void print(int a, int b, int c) {
    cout << "int int int" << endl;
}
void print(int a, int b,  int c, int d) {
    cout << "int int" << endl;
}

// 注意事项:函数返回值类型不同不可作为函数重载的条件
int main()
{
    print(1);
    print(1.0);

    print(1.0, 1);
    print(1, 1.0);

    print(1, 1, 1);
    print(1, 1, 1, 1);
    
    return 0;
}

3.4 函数重载-注意事项

  • 引用作为重载条件
  • 函数重载碰到函数默认参数

示例:

cpp 复制代码
#include <iostream>
using namespace std;

// 函数重载注意事项
// 1.引用作为重载的条件
void fun(int& a) {
    cout << "func(int& a)调用" << endl;
}

void fun(const int& a) {
    cout << "func(const int& a)调用" << endl;
}

// 2.函数重载碰到默认参数
void func(int a) {
    cout << "func(int a)调用" << endl;
}
void func(int a, int b = 10) {
    cout << "func(int a, int b = 10)调用" << endl;
}

int main() {

    // func(int& a)调用
    int a = 10;
    fun(a);

    // func(const int& a)调用
    const int b = 10;
    fun(b);
    fun(10);

    // 当函数调用碰到默认参数会出现二义性报错
    // func(10);   // 错误❌,默认参数不能省略
    func(10,10);    //  正确
    return 0;
}
相关推荐
HugoStudio_SWAN23 分钟前
洛谷 B4450 / B3867 / B3923 智慧购物、储蓄与做题——从程序到生活
c++·学习·程序人生·算法·生活
猎头南楼2 小时前
VLA 模型落地端侧:从架构选型到量化部署的工程实践笔记
笔记·架构·大模型
会周易的程序员2 小时前
5Draft(五帝)测试报告
服务器·c++·分布式·raft·共识算法·共识·算力服务器
Capricorn19882 小时前
日志级幻觉排障:GPT-6 Astra 迈入 AGI 时代,知芽 Notebook Skill 如何以引用校验与零命中诚实弃权解决长文失忆
论文阅读·人工智能·笔记·gpt·agi
UIU1142 小时前
scanf与cout的误区:探究其内部的机制
c++·学习·c#·scanf
闻缺陷则喜何志丹2 小时前
【栈 运算系统】P3719 [AHOI2017初中组] rexp|普及+
c++·算法··洛谷·运算系统
疯狂打码的少年3 小时前
【数据库技术】多值依赖与第四范式(4NF)
数据库·笔记·算法
tq10863 小时前
算法的另一面
笔记
bnmoel3 小时前
C++ 基础入门篇(一):命名空间,输入&输出,缺省参数,函数重载
c++·函数重载·语法·命名空间·缺省参数
Zixhy3 小时前
多点巡检机器人项目技术总结
linux·c++·机器人·自动驾驶