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;
}
相关推荐
EverestVIP1 小时前
C++ 成员函数的指针
c++
俺不要写代码1 小时前
线程启动、结束,创建线程多法、join,detach,线程的移动语义
服务器·开发语言·网络·c++
雾岛听蓝1 小时前
Qt Widget控件属性详解
开发语言·经验分享·笔记·qt
好家伙VCC1 小时前
# 发散创新:用 Rust实现高性能物理引擎的底层架构设计与实战在游戏开发、虚拟仿真和机器人控
java·开发语言·python·rust·机器人
boonya1 小时前
一文读懂MCP:AI连接万物的“USB-C接口”
c语言·开发语言·人工智能
liliangcsdn1 小时前
多轮对话长上下文-向量检索和混合召回示例
开发语言·数据库·人工智能·python
思麟呀1 小时前
应用层协议HTTP
linux·服务器·网络·c++·网络协议·http
leoZ2311 小时前
金仓老旧项目改造-10
开发语言·前端·人工智能·python·金仓
Tina学编程2 小时前
[HOT 100]今日一练------划分字母区间
算法·hot 100
RTC老炮2 小时前
RaptorQ前向纠错算法架构分析
网络·算法·架构·webrtc