6 函数
时间:2023-9-18 22:31 作者:wen 分类: C++
[toc]
函数
概述
作用:将一段经常使用的代码封装起来,减少重复代码。
一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。
函数的定义
函数的定义一般有五个步骤:
- 返回值类型
- 函数名
- 参数列表
- 函数体语句
- return 表达式
语法:
返回值类型 函数名(参数列表)
{
函数体语句
return 表达式
}
函数的调用
功能:使用定义好的函数。
语法:函数名(参数)
示例:
#include <iostream>
using namespace std;
// 加法函数
int add(int numA, int numB)
{
return numA + numB;
}
int main()
{
int a = 10, b = 20;
cout << add(a, b) << endl;
system("pause");
return 0;
}
值传递
- 所谓值传递,就是函数调用时,实参将数值传入给形参。
- 值传递时,如果形参发生变化,并不会影响实参。
示例
#include <iostream>
using namespace std;
void swap(int numA, int numB)
{
cout << "交换前:" << endl;
cout << "numA = " << numA << endl;
cout << "numB = " << numB << endl;
int temp = numA;
numA = numB;
numB = temp;
cout << "交换后:" << endl;
cout << "numA = " << numA << endl;
cout << "numB = " << numB << endl;
}
int main()
{
int a = 10, b = 20;
swap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
system("pause");
return 0;
}
函数的常见样式
常见的函数样式有四种:
- 无参无返
- 有参无返
- 无参有返
- 有参有返
示例
#include <iostream>
using namespace std;
// 1.无参无返
void testA()
{
cout << "hello world" << endl;
}
// 2.有参无返
void testB(string a)
{
cout << a << endl;
}
// 3.无参有返
int testC()
{
return 20;
}
// 4.有参有返
int testD(int a, int b)
{
return a + b;
}
int main()
{
int a = 10, b = 20;
testA();
testB("hello world");
cout << testC() << endl;
cout << testD(10, 20) << endl;
system("pause");
return 0;
}
函数的声明
作用:让代码结构更加清晰。
函数分文件编写一般有4个步骤:
- 创建后缀名为.h的头文件。
- 创建后缀名为.cpp的源文件。
- 在头文件中写函数的声明。
- 在源文件中写函数的定义。
示例
// swap.h
#pragma once
#include <iostream>
using namespace std;
// 函数声明
void swap(int a, int b);
// swap.cpp
#include "swap.h"
// 函数定义
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}
// main.cpp
#include <iostream>
#include "swap.h"
int main()
{
int a = 10, b = 20;
swap(a, b);
system("pause");
return 0;
}
标签: C/C++