本节内容:函数、vs2022分文件编写函数结构
main:C++study_06.cpp
#include <iostream>
using namespace std;
#include "swap_1.h"
//函数
//实现加法功能的函数
int add(int num1, int num2) //num1和num2为形参
{
int sum = num1 + num2;
return sum;
}
//值传递
//定义函数,实现两个数字进行交换函数
//如果函数不需要返回值,声明的时候可以写void
void swap(int num1, int num2)
{
cout << "交换前num1 = " << num1 << " num2 = " << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后num1 = " << num1 << " num2 = " << num2 << endl;
//return;返回值不需要的时候,return可写可不写。
}
//函数常见样式
//1、 无参无返
void test01()
{
//void a = 10; //无类型不可以创建变量,原因无法分配内存
cout << "this is test01" << endl;
//test01(); 函数调用
}
//2、 有参无返
void test02(int a)
{
cout << "this is test02" << endl;
cout << "a = " << a << endl;
}
//3、无参有返
int test03()
{
cout << "this is test03 " << endl;
return 10;
}
//4、有参有返
int test04(int a, int b)
{
cout << "this is test04 " << endl;
int sum = a + b;
return sum;
}
//函数的声明
/*
作用:告诉编译器函数名称及如何调用函数。
函数的实际主体可以单独定义。
函数的声明可以多次,但是函数的定义只能有一次。
*/
//比较函数,实现两个整型数字进行比较,返回较大的值
//定义
int max(int a, int b)
{
return a > b ? a : b;
}
//提前告诉函数的存在,可以利用函数的声明
int max(int a, int b);
//函数声明主要是当函数的定义在main后面时,
//防止main里调用该函数时找不到它,所以要在main前面声明一下。
//函数的分文件编写
/*
作用:让代码结构更加清晰
函数分文件编写一般有4个步骤:
1. 创建后缀名为.h的头文件
2. 创建后缀名为.cpp的源文件
3. 在头文件中写函数的声明
4. 在源文件中写函数的定义
*/
//分文件编写以交换数字函数swap_1为例:
int main()
{
//在main中调用add
int a = 10;
int b = 20;
int c = add(a, b); //a和b为实参,调用函数add时,实参的值会传入形参
cout << "c = " << c << endl;
int a = 10;
int b = 20;
swap(a, b);
//当做值传递的时候,函数的形参发生改变,并不会影响实参
cout << a << b << endl;
//调用max函数
int a = 10;
int b = 20;
cout << max(a, b) << endl;
//调用源文件里写的swap_1函数
int a = 10;
int b = 20;
swap_1(a, b);
system("pause");
return 0;
}
源文件:swap_1.cpp
#include "swap_1.h" //双引号代表自定义的头文件
//函数的定义
void swap_1(int num1, int num2)
{
cout << "交换前num1 = " << num1 << " num2 = " << num2 << endl;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后num1 = " << num1 << " num2 = " << num2 << endl;
}
头文件:swap_1.h
#include <iostream>
using namespace std;
//函数声明
void swap_1(int num1, int num2);
一节一篇代码,简单粗暴,适合快速学习/复习C++基础知识。