C++:函数

目录

一、函数

1.1 内联函数

1.2 函数重载 overload

1.3 默认参数(缺省参数)

1.4 哑元函数

一、函数

1.1 内联函数

C++引入内联函数来代替C语言中宏定义的函数,可以解决程序中函数调用的效率问题。内联函数在编译时会直接把函数体中的内容展开到主函数中,因此程序运行时可以消除普通函数的额外开销。

使用内联函数的要求如下:

  • 内联函数的代码长度限制在1-5行,且不能包含复杂的循环或流程控制语句。
  • 内联函数最好是频繁使用的函数。
  • 使用关键字inline放在函数定义的前面。
  • 成员函数默认为内联函数
#include <iostream>

using namespace std;

// 先声明
void show_long(string s1,string s2);

int main()
{
    show_long("aaaaa","bbb");

    return 0;
}

// 再定义
inline void show_long(string s1,string s2)
{
    s1.size() > s2.size() ? cout << s1 : cout << s2;
}

1.2 函数重载 overload

C++允许同一个函数名称定义多个函数,这种用法就是函数重载。

函数重载的要求是函数的名称相同,但是参数不同。参数不同可以是数量不同,也可以是类型不同,返回值类型与函数重载毫无关系。

#include <iostream>

using namespace std;


void print(string s)
{
    cout << "1" << endl;
}

void print(int i)
{
    cout << "2" << endl;
}

void print(int i1,int i2)
{
    cout << "3" << endl;
}


int main()
{
    print(""); // 1
    print(1,1); // 3
    print(2); // 2

    return 0;
}

需要注意的是,下面的代码从语法上讲可以通过,但是代码的可读性上来讲并不建议。另一方面,在某些特定的情况下,会对编译器产生误导,导致编译不通过。

#include <iostream>

using namespace std;


void print(long s)
{
    cout << "1" << endl;
}

void print(int i)
{
    cout << "2" << endl;
}

int main()
{
    print(0);

    return 0;
}

需要注意的是,函数重载支持构造函数。

1.3 默认参数(缺省参数)

C++中允许给函数的参数设定默认值(缺省值),调用时如果不传入参数,则参数使用默认值;调用时如果传入参数,传入的参数可以替换默认值。

参数的默认值既可以写在函数声明处,又可以写在函数定义处,但是建议只写在一处。

参数的默认值遵循“向右原则(向后原则)”,即当函数的某个参数设定了默认值后,其右边(后边)的参数都必须设定默认值。

#include <iostream>

using namespace std;

void show1(int a,int b=3);

void show1(int a,int b)
{
    cout << "1 " << a << b << endl;
}

void show2(int a,int b);

void show2(int a=4,int b=5)
{
    cout << "2 " << a << b << endl;
}

void show3(int a,int b=0,int c=8)
{
    cout << "3 " <<  a << b << c << endl;
}

int main()
{
    show1(1); // 1 13
    show1(1,2); // 1 12

    show2(); // 2 45
    show2(1); // 2 15
    show2(1,2); // 2 12

    show3(1); // 3 108
    show3(1,2); // 3 128
    show3(1,2,3); // 3 123

    return 0;
}

可以看到,参数的默认值与函数重载都可以实现同一个函数名称接受不同参数的效果,但是有以下几个区别:

1. 默认参数无法处理参数类型不同的情况。

2. 默认参数无法针对不同个数的传入参数有不同的逻辑响应。

建议优先使用默认参数,如果默认参数无法实现目标功能再使用函数重载。非必要不得将函数重载与默认参数同时使用,因为非常容易出现二义性问题(ambiguous)。

#include <iostream>

using namespace std;

void show()
{
    cout << "a" << endl;
}

void show(int a = 0)
{
    cout << "b" << endl;
}


int main()
{
//    show(); 错误

    return 0;
}

1.4 哑元函数

如果一个函数的参数只有类型且没有名字,则这个函数就是哑元函数,这个参数被称为哑元。

#include <iostream>

using namespace std;

void print(string);

void print(string)
{
    cout << "1" << endl;
}

void print(int)
{
    cout << "2" << endl;
}


int main()
{
    print(12); // 2
    print("12"); // 1

    return 0;
}

哑元函数在特定的场景下具有一定作用:

1. 保持函数的向前兼容特性

2. 区分重载的函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值