栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++函数

目录

1 概述

2 函数的定义

3 函数的调用

4 值传递

5 函数的常见样式

6 函数的声明


1 概述

作用:将一段经常使用的代码封装起来,减少重复代码。一个较大的程序,一般分为若干个程序块,每个模块实现特定的功能。

2 函数的定义

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

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

    return表达式
}
#include
using namespace std;


int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;

}

3 函数的调用

功能:使用定义好的函数

语法:函数名(参数)

#include
using namespace std;



//num1,num2为形参
int add(int num1, int num2)
{
	int sum = num1 + num2;
	return sum;

}
int main() {

	int a = 10;
	int b = 20;
    //a,b为实参
	int c = add(a, b);

	cout << "c = " << c << endl;

	system("pause");
	return 0;
}

4 值传递
  • 所谓值传递,就是函数调用时实参将数值传入给形参;
  • 值传递时,如果形参发生改变,并不会影响实参
#include
using namespace std;



//如果函数不需要返回值,声明的时候可以写void
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;
}
int main() {

	int a = 10;
	int b = 20;

	swap(a, b);

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

	system("pause");
	return 0;
}

5 函数的常见样式

常见的函数样式有四种:

  1. 无参无返
  2. 有参无返
  3. 无参有返
  4. 有参有返
#include
using namespace std;



//1.无参无返
void demo1()
{
	cout << "this is a demo" << endl;
}
//2.有参无返
void demo2(int a)
{
	cout << "a = " << a << end;
}
//3.无参有返
int demo3()
{
	return 1000;
}
//4.有参有返
int demo4(int a)
{
	cout << "a = " << a << endl;
	return a;
}


int main() {

	int a = 10;
	demo1();
	demo2(a);
	int num1 = demo3();
	cout << "num1 = " << num << endl;

	int num2 = demo4(1000);

	system("pause");
	return 0;
}

6 函数的声明

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

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

#include
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;
}

7 函数的分文件编写

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

函数分文件编写一般有四个步骤:

  1. 创建后缀名为.h的头文件
  2. 创建后缀名为.cpp的源文件
  3. 在头文件中写函数的声明
  4. 在源文件中写函数的定义
//头文件
#include
using namespace std;

void swap(int a, int b);
//源文件
#include"swap.h"

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;
}
//执行文件
#include
using namespace std;
#include"swap.h"

int main() {

	int a = 10;
	int b = 20;

	swap(a, b);

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

	system("pause");
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/433401.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号