CH06_函数


概述

作用:将一段可复用的代码封装起来,减少代码重复。

一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。

函数的定义

函数的定义一般主要有5个步骤:

  1. 返回值类型
  2. 函数名
  3. 参数列表
  4. 函数体语句
  5. 返回值

语法:

返回值类型 函数名(参数列表){
    函数体语句
    return 返回值;
}
  • 返回值类型:一个函数可以返回一个值
  • 函数名:给函数起的名称
  • 参数列表:使用该函数时,传入的数据
  • 函数体语句:花括号内的代码,函数内需要执行的语句
  • return表达式:和返回值类型挂钩,函数执行完后,返回相应的数据。

示例:

int add(int num1, int num2) {
	int sum = num1 + num2;
	return sum;
}

函数的调用

功能:调用定义好的函数

语法:参数名(参数)

示例:

#include <iostream>
using namespace std;


int add(int num1, int num2) {
	int sum = num1 + num2;
	return sum;
}

int main() {
	int num1 = 15, num2 = 5;

	//调用方法
	int sum = add(num1, num2);
	
	//显示结构
	cout << "结果:" << sum << endl;

	system("pause");
	return 0;
}

值传递

值传递,就是函数调用时实参将数值传入给形参

值传递时,在方法中对参数改变,对实参不会有任何影响。

示例:

#include <iostream>
using namespace std;

void swap(int num1, int num2) {
	int temp = num1;
	num1 = num2;
	num2 = temp;

	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;
}

int main() {
	int num1 = 15, num2 = 5;

	//调用前
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;
	cout << "---------------------------" << endl;

	//调用方法
	swap(num1, num2);
	cout << "---------------------------" << endl;
	

	//调用后
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;
	cout << "---------------------------" << endl;

	system("pause");
	return 0;
}

函数的常见样式

常见形式:

  1. 无参无返回值
  2. 有参无返回值
  3. 无参有返回值
  4. 有参有返回值

示例:

#include <iostream>
using namespace std;

void fun1() {
	cout << "调用了无参无返回值的方法" << endl;
}

void fun2(int num) {
	cout << "调用了有参无返回值的方法" << endl;
	cout << "参数num:" <<num<< endl;
}

int fun3() {
	cout << "调用了无参有返回值的方法" << endl;
	cout << "返回值:10"  << endl;

	return 10;
}

int fun4(int num) {
	cout << "调用了有参有返回值的方法" << endl;
	cout << "参树:"<<num << endl;
	cout << "返回值:" << (num+5) << endl;

	return num+5;
}



int main() {
	
	int num = 10;

	//fun1();
	//fun2(num);
	//fun3();
	fun4(num);

	system("pause");
	return 0;
}

函数的声明

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

函数的声明可以多次,但是函数的定义只能有一次。

示例:

#include <iostream>
using namespace std;


//函数声明
int max(int a, int b);
int max(int a, int b);

//函数定义
int max(int a, int b) {
	return a > b ? a : b;
}


int main() {

	int a = 10, b = 20;

	cout << "最大值:" << max(a, b) << endl;

	system("pause");
	return 0;
}

函数的分文件编写

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

步骤:

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

示例:

//头文件
#pragma once
#include<iostream>
using namespace std;

//实现两个数字交换的函数的声明
void swap(int a, int b);


#include "swap.h"

//函数的定义
void swap(int a, int b) {
	int temp = a;
	a = b;
	b = temp;

	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

#include<iostream>
#include "swap.h" //引入头文件

int main() {

	//调用方法
	swap(10, 20);

	system("pause");
	return 0;
}
posted on 2024-06-11 20:31  熊猫_大侠  阅读(11)  评论(0编辑  收藏  举报