c++函数以及函数分文件编写

1.函数

1.1格式

返回值类型 函数名 (参数列表)//返回值类型指的是return过去的类型
{
函数体语句
return 表达式
}

1.2常见的函数样式

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

#include<iostream>
using namespace std;
int add(int num1,int num2)
	{ //此时的num1和num2没有真实数据,简称形参
		int sum = num1 + num2;
		return sum;
	}
//函数声明 函数开头粘贴过来加分号
void swap(int num1, int num2);
	int main()
{
	//函数调用: 函数名 (参数)
	//我们管a,b叫做实参
		int a = 10;
		int b = 20;
		int sum = add(a, b);
		cout << "sum = " << sum << endl;
		swap(a, b);
	system("pause");
	return 0;
}
	//形参改变不会影响实参
	//除了在函数中使用指针进行地址传递的操作时,可能会改变
	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;
	}

2.函数分文件编写

2.1分文件编写

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

swap.h

#include <iostream>
using namespace std;//得加上框架不然cout会报错
//函数声明
void swap2(int num1, int num2);

swap.cpp

#include "swap.h"//""代表自定义的一个文件

void swap2(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;
}

main.cpp

//void swap2(int num1, int num2);
#include<iostream>
using namespace std;
#include "swap.h"
int main()
{
	int a = 20;
	int b = 10;
	swap2(a,b);
	system("pause");
	return 0;
}
//void swap2(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;
//}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值