0%

C++的函数

概述

将一串经常会使用的代码封装起来,减少重复代码。一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。

函数的定义

函数的定义一般分为5个步骤:

  • 返回值类型

  • 函数名

  • 参数表列

  • 函数体语句

  • return表达式

    语法:

    1
    2
    3
    4
    5
    6
    返回值类型 函数名  (参数列表)
    {
    函数体语句

    return表达式
    }

例如

实现一个加法函数

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<iostream>
using namespace std;
int add(int a,int b)
{
int s=a+b;
return s;
}
int main()
{


return 0;
}

函数的调用

语法:函数名(参数)

例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
using namespace std;
int add(int a,int b)
{
int s=a+b;
return s;
}
int main()
{
int m,n;
cin>>m>>n;
int c=add(m,n); //此处m和n均为整型,叫实际参数,简称实参
cout<<c<<endl;
return 0;
}

注意:定义时a,b并没有真实数据,只是一个形式,叫做形参。当调用函数时,实参的值会传给形参

值传递

定义:值传递就是函数调用时实参将数值传给形参

形参发生变化,不会影响实参

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
void ex(int a,int b)
{
cout<<"交换前第一个数"<<a<<endl;
cout<<"交换前第二个数"<<b<<endl;
int t=a;
a=b;
b=t;
cout<<"交换后第一个数"<<a<<endl;
cout<<"交换后第二个数"<<b<<endl;
//return s;
}
int main()
{
int m,n;
cin>>m>>n;
ex(m,n);
cout<<m<<n<<endl;//实参不变,也就是m还是第一个输入的数,变化的是形参
return 0;
}

函数常见样式

  • 无参无返

  • 有参有返

  • 无参有返

  • 有参有返

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    #include<iostream>
    using namespace std;
    //无参无返
    void test1()
    {
    cout<<"无参无返"<<endl;
    }
    //有参无返
    void test2(int a)
    {
    cout<<"有参无返 a="<<a<<endl;
    }
    //无参有返
    int test3()
    {
    cout<<"无参有返"<<endl;
    return 555;
    }
    //有参有返
    int test4(int t)
    {
    cout<<"有参有返 t="<<t<<endl;
    return 666;
    }

    int main()
    {
    test1();

    int n=100;
    test2(n);//传参100

    int c;
    c=test3();
    cout<<c<<endl;

    int d;
    d=test4(100);//100传给t 返回666
    cout<<d<<endl;

    return 0;
    }

函数的声明

作用:告诉编译器函数名称及如何调用函数。函数的实际本体可以单独定义。

  • 函数的声明可以多次,但是函数的定义只能有一次
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;

int m(int a,int b)
{
return a>b?a:b;
}
int main()
{
int a=10,b=20;
cout<<m(a,b)<<endl;
return 0;
}

若不声明,定义只能在main函数之前,如上。

定义后

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

int m(int a,int b);
int m(int a,int b);
int m(int a,int b);
int m(int a,int b);//声明(可以有多次,如此,一般就写一次.定义不能这样)

int main()
{
int a=10,b=20;
cout<<m(a,b)<<endl;
return 0;
}

int m(int a,int b)
{
return a>b?a:b;
}

函数的分文件编写

作用:让代码块结构更加清晰

函数分文件编写一般有4个步骤

  1. 创建后缀名为**.h**的头文件
  2. 创建后缀名为**.cpp**的源文件
  3. 在头文件中写函数声明
  4. 在源文件中写函数定义

示例

头文件 max.h

1
2
3
4
#include<iostream>
using namespace std;
int m(int a,int b);//声明

源文件max.cpp

1
2
3
4
5
int m(int a,int b)//定义
{
return a>b?a:b;
}

main.cpp

1
2
3
4
5
6
7
8
#include"max.h"
int main()
{
int a=10,b=20;
cout<<m(a,b)<<endl; //直接引用
return 0;
}