C++学习之函数

函数

概述

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

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

函数的定义

函数的定义一般主要由五个步骤:

  1. 返回值类型
  2. 函数名
  3. 参数列表
  4. 函数条件语句
  5. return表达式

语法:

返回值类型 函数名 (参数列表)
{
	函数条件语句
        
        return 返回值;
}

函数的调用

功能:使用定义好的函数

语法:函数名(参数)

示例:

#include<iostream>;
using namespace std;

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

int main() {

	int num1 = 0;
	int num2 = 0;
	cout << "请输入您要计算的第一个数字:" << endl;
	cin >> num1;
	cout << "请输入您要计算的第二个数字:" << endl;
	cin >> num2;

	cout << add(num1, num2) << endl;

	system("pause");

	return 0;

}

总结:函数定义里小括号内称为形参,函数调用时传入的参数称为实参

值传递

  • 所谓值传递,就是函数调用时实参将数值传入给形参
  • 传值递时,如果形参发生,并不会影响实参

示例:

void swap(int num1, int num2)
{
	cout << "交换前:" << endl;
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;
	int a = 0;
	a = num1;
	num1 = num2;
	num2 = a;

	cout << "交换后:" << endl;
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;

	return;
}
int main() {

	int num1 = 0;
	int num2 = 0;
	cout << "请输入您要计算的第一个数字:" << endl;
	cin >> num1;
	cout << "请输入您要计算的第二个数字:" << endl;
	cin >> num2;

	swap(num1, num2);
	cout << num1 << endl;
	cout << num2 << endl;

	system("pause");

	return 0;

}

函数的常见样式

常见的函数样式有4种

  1. 无参无返
  2. 有参吴返
  3. 无参有返
  4. 有参有返

示例:

//1.无参函数
void test1() {
	cout << "我是一个无参函数" << endl;
}
//2.有参无返
void test2(int num1, int num2)
{
	cout << "交换前:" << endl;
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;
	int a = 0;
	a = num1;
	num1 = num2;
	num2 = a;

	cout << "交换后:" << endl;
	cout << "num1:" << num1 << endl;
	cout << "num2:" << num2 << endl;

	return;
}
//3.无参有返
int test3() 
{
	cout << "这是无参有返" << endl;

	return 2;
}
//有参有返
int test4(int num1, int num2)
{
	return num1 + num2;
}

int main(){
    test1();
	test2(2, 22);
	int a = test3();
	int b = test4(4, 6);
	cout << a << endl;
	cout << b << endl;
	system("pause");

	return 0;
}

函数的声明

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

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

示例:

#include<iostream>
using namespace std;

//函数的声明
int test(int num12, int num2);


int main() {

    int c = test(4,6);
	cout << c << endl;

	system("pause");

	return 0;
}

int test(int num1, int num2)
{
	return num1 > num2 ? num1 : num2;
}

函数的分文件编写

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

韩式分文件别写一般有四个步骤

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值