C++函数提高

1.函数默认参数

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

//函数默认参数
//如果自己传入数据,就用自己的数据,否则就用默认值
int func(int a, int b=20, int c=30)
{
    return a + b + c;
}



//注意事项
//1.如果某个位置已经有了默认参数,那么从这个位置往后,从左到右都必须有默认值
//错误案例:
/*int func2(int a, int b = 10, int c)
{
    return a + b + c;
}*/

//2.如果函数声明有默认参数,函数实现就不能有默认参数(二义性)
//声明和实现只能有一个有默认参数
//错误案例:
/*
int func2(int a = 10, int b = 10);

int func2(int a = 10, int b = 10)
{
    return a + b;
}
*/
int main()
{
    cout << func(10) << endl;
    cout << func(10,30) << endl;

    //cout << func2(10, 20) << endl;

    system("pause");

    return 0;
}

2.函数占位参数

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

//占位参数
//返回值类型 函数名(数据类型){}

//目前阶段的占位参数,还用不到
//占位参数,还可以有默认参数
void func(int a, int)
{
    cout << "this is func" << endl;
}

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

    system("pause");

    return 0;
}

3.函数重载

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

//函数重载
//可以让函数名相同,提高复用性

//函数重载的满足条件
//1.同一个作用域下
//2.函数名称相同
//3.函数参数类型不同,或者个数不同,或者顺序不同
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,double b)
{
    cout << "func(int a,double b)的调用" << endl;
}

void func(double b, int a)
{
    cout << "func(double b, int a)的调用" << endl;
}
//注意事项
//函数的返回值不可以作为函数重载的条件
int func(double b, int a)
{
    cout << "func(double b, int a)的调用" << endl;
}

int main()
{
    func();
    func(10);
    func(3.14);
    func(10, 3.14);
    func(3.14, 10);
      
    system("pause");
    return 0;
}
相关推荐
上单带刀不带妹2 分钟前
手写 Vue 中虚拟 DOM 到真实 DOM 的完整过程
开发语言·前端·javascript·vue.js·前端框架
Kaltistss22 分钟前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭26 分钟前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.82435 分钟前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug38 分钟前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒40 分钟前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
-凌凌漆-43 分钟前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼43 分钟前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
小刘同学3211 小时前
C++11 特性
c++·c11新特性