前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >c++之函数

c++之函数

作者头像
西西嘛呦
发布2020-08-26 15:24:18
4070
发布2020-08-26 15:24:18
举报

作用:将一段常用的代码封装起来,减少重复代码;

函数定义5个步骤:返回值类型、函数名、参数列表、函数体语句、return表达式

代码语言:javascript
复制
int add(int num1,int num2){
    int res = num1 + num2;
    return res;  
}

一、函数声明

通过函数声明,表明有这么一个函数存在:

代码语言:javascript
复制
#include<iostream>
using namespace std;
//函数声明,可以只声明参数的类型
//由于进行了函数声明,虽然max函数在主函数之后,此时仍然是可以被调用的
int max(int, int);

int main() {
    int a = 1;
    int b = 2;
    int res = max(a, b);
    cout << res << endl;
    system("pause");
    return 0;
}

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

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

二、函数的分文件编写

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

  • 创建后缀名为.h的头文件
  • 创建后缀名为.cpp的源文件
  • 在头文件中写函数声明
  • 在源文件中实现函数定义

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

目录结构:

max.h

代码语言:javascript
复制
#include<iostream>
using namespace std;
int max(int, int);

second.cpp

代码语言:javascript
复制
#include "max.h"


int main() {
    int a = 1;
    int b = 2;
    int res = max(a, b);
    cout << res << endl;
    system("pause");
    return 0;
}

int max(int a, int b) {
    int res = a > b ? a : b;
    return res;
}

三。值传递和引用传递

1.值传递

什么是值传递?

在函数调用时将实参的值传递给形参;

有什么特点?

值传递时,如果形参发生变化,则不会影响原来实参的值。

代码语言:javascript
复制
#include <iostream>
using namespace std;

void swap(int num1, int num2) {
    cout << "交换之前num1的值:" << num1 << endl;
    cout << "交换之前num2的值:" << num2 << endl;
    int tmp = num1;
    num1 = num2;
    num2 = tmp;
    cout << "交换之后num1的值:" << num1 << endl;
    cout << "交换之后num2的值:" << num2 << endl;
}

int main() 
{
    int a = 1;
    int b = 2;
    cout << "实参未传入之前a的值:" << a << endl;
    cout << "实参未传入之前b的值:" << b << endl;
    swap(a, b);
    cout << "实参传入之后a的值:" << a << endl;
    cout << "实参传入之后b的值:" << b << endl;
    system("pause");
    return 0;
}

输出:

2.引用传递

什么是引用传递?

在函数调用时将实参的引用(即指针)传递给形参;

引用传递的特点?

引用传递时,如果形参发生变化,则同时会影响原来实参的值。

代码语言:javascript
复制
#include <iostream>
using namespace std;

void swap(int* num1, int* num2) {
    cout << "交换之前num1的值:" << *num1 << endl;
    cout << "交换之前num2的值:" << *num2 << endl;
    int tmp = *num1;
    *num1 = *num2;
    *num2 = tmp;
    cout << "交换之后num1的值:" << *num1 << endl;
    cout << "交换之后num2的值:" << *num2 << endl;
}


int main() 
{
    int a = 1;
    int b = 2;
    int* p1 = &a;
    int* p2 = &b;
    cout << "实参未传入之前a的值:" << a << endl;
    cout << "实参未传入之前b的值:" << b << endl;
    swap(p1, p2);
    cout << "实参传入之后a的值:" << a << endl;
    cout << "实参传入之后b的值:" << b << endl;
    system("pause");
    return 0;
}

输出:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-12-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档