【C++基础语法入门】6 函数

黑马程序员匠心之作|C++教程从0到1入门编程
学习笔记
目标:对C++有初步了解,能够有基础编程能力
案例:通讯录管理系统

6.1 概述

作用:将一段经常使用的代码封装起来,减少重复代码

6.2 函数的定义

主要有5个步骤:

  1. 返回值类型
  2. 函数名
  3. 参数表列
  4. 函数体语句
  5. return表达式
    语法:
返回值类型 函数名(参数列表)
{
	函数体语句

	return表达式
}

示例:加法函数

//函数定义的时候num1,num2没有确定的函数,简称形参
int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;
}

6.3 函数的调用

int main()
{
	//a,b称为实参
	//当调用函数的时候,实参的数会传递给形参
	
	int a = 10;
	int b = 10;
	int c = add(a, b);

	cout << c << endl;

	system("pause");
	
	return 0;
}

6.4 值传递

所谓值传递,就是函数调用的时候实参将参数值传入给形参
注意:值传递时,如果形参发生改变,不影响实参

#include <iostream>
using namespace std;

void swap(int num1, int num2) {
	cout << "置换前a:" << num1 << endl;
	cout << "置换前b:" << num2 << endl;

	int tmp = num1;
	num1 = num2;
	num2 = tmp;

	cout << "置换后a:" << num1 << endl;
	cout << "置换后b:" << num2 << endl;
}

int main()
{
	int a = 10;
	int b = 20;

	cout <<"开始的数值a:"<< a << endl;
	cout <<"开始的数值b:"<< b << endl;

	swap(a, b);

	cout << "最后的a:" << a << endl;
	cout << "最后的b" << b << endl;

	system("pause");

	return 0;
}

输出

开始的数值a:10
开始的数值b:20
置换前a:10
置换前b:20
置换后a:20
置换后b:10
最后的a:10
最后的b:20

由结果我们看出,结果除的a和b并没有改变,这是因为实参并不会受形参的改变而改变。

6.5 函数的常见样式

常见的函数样式:

  1. 无参无返
void test01()
{
	cout << "this is test01"<<endl;
}
int main()
{
	test01();//调用
	system("pause");
	return 0;	
}
  1. 有参无返
void test01(int a)
{
	cout << "this is test02 a ="<<a<<endl;
}
int main()
{
	test01();//调用
	system("pause");
	return 0;	
}
  1. 无参有返
void test01()
{
	cout << "this is test03 <<endl;
	return 1000;
}
int main()
{ 
	test03();
	system("pause");
	return 0;	
}
  1. 有参有返
void test01(int a)
{
	cout << "this is test04 <<endl;
	return a;
}
int main()
{ 
	test04(1000);
	system("pause");
	return 0;	
}

6.6 函数的声明

由于代码是从上到下一句句运行的,因此如果想让函数的定义在代码的任意位置,需要使用函数的声明。
作用:提前告诉编译器函数的存在,可以利用函数的声明。
注意:声明可以写多次,定义只能有一次
示例:实现两个整型数字进行比较,返回较大的值

#include <iostream>
using namespace std;

//提前告诉编译器函数的存在,可以利用函数的声明
//函数的声明
int max(int a, int b);

int main()
{
	int a = 10;
	int b = 20;

	cout << max(a, b) << endl;

	system("pause");

	return 0;
}

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

6.7 函数的分文件编写

  1. 创建.h后缀名的头文件swap.h
  2. 创建.cpp后缀名的源文件swap.cpp
  3. 在头文件中写函数的声明
#pragma once
void swap(int a, int b);
  1. 在源文件中写函数的定义
#include"swap.h"
#include<iostream>
using namespace std;

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

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

最后,在main函数的源文件中加上

#include"swap.h"

成功

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值