【C++基础语法入门】6 函数
黑马程序员匠心之作|C++教程从0到1入门编程
学习笔记
目标:对C++有初步了解,能够有基础编程能力
案例:通讯录管理系统
6.1 概述
作用:将一段经常使用的代码封装起来,减少重复代码
6.2 函数的定义
主要有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 函数的常见样式
常见的函数样式:
- 无参无返
void test01()
{
cout << "this is test01"<<endl;
}
int main()
{
test01();//调用
system("pause");
return 0;
}
- 有参无返
void test01(int a)
{
cout << "this is test02 a ="<<a<<endl;
}
int main()
{
test01();//调用
system("pause");
return 0;
}
- 无参有返
void test01()
{
cout << "this is test03 <<endl;
return 1000;
}
int main()
{
test03();
system("pause");
return 0;
}
- 有参有返
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 函数的分文件编写
- 创建.h后缀名的头文件swap.h
- 创建.cpp后缀名的源文件swap.cpp
- 在头文件中写函数的声明
#pragma once
void swap(int a, int b);
- 在源文件中写函数的定义
#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"
成功