C++基础(5)——函数

1.值传递

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

#include<iostream>
using namespace std;
#include<string>

//实现两个数字进行交换的函数
void swap(int num1, int num2) {
	cout << "交换前的数据为:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;

	int temp = num1;
	num1 = num2;
	num2 = temp;

	cout << "交换后的数据为:" << endl;
	cout << "num1=" << num1 << endl;
	cout << "num2=" << num2 << endl;
}

void main() {
	int a = 10;
	int b = 20;
	swap(a, b);
	cout << "a=" <<a<< endl;
	cout << "b=" << b << endl;
}

 2.函数的声明

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

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

#include<iostream>
using namespace std;
#include<string>

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

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

void main() {
	int a = 10;
	int b = 20;
	int c = max(a, b);//函数调用
	cout<<c<<endl;
}

3.函数的分文件编写

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

函数分文件编写的步骤:

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

案例:实现两个数字交换的函数

swap.h头文件为:

#pragma once
#include<iostream>
using namespace std;

void swap(int a, int b);//函数的声明

swap.cpp源文件为:

#include<iostream>
#include"swap.h"
using namespace std;

void swap(int a, int b) {
	int temp = a;
	a = b;
	b = temp;
	cout << "a=" << a << endl;
	cout << "b=" << b << endl;
}

test.cpp测试文件为:

#include<iostream>
#include"swap.h"
using namespace std;

void main() {
	int a = 10;
	int b = 20;
	swap(a, b);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI炮灰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值