按值传递--地址传递--指针传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//按值传递
#include <bits/stdc++.h>
using namespace std;
/*
自定义函数必须在调用该函数之前声明
声明时可以不写函数体,但在后面需要将函数体补充完整
按值传递的形参与调用函数类型一致
*/
int sum(int a,int b){
    int n=a+b;
    a+=1;
    return n;
}
int main(){
    int x,c=3,d=5;
    //调用sum函数,并将计算结果赋值给变量X
    x=sum(c,d);
    cout<<"x="<<x<<",c="<<c;
    return 0;
}
 
//地址传递
#include <bits/stdc++.h>
using namespace std;
/*
那些参数是地址传递,就在那个变量前加&号
计算时写的是其变量,不加&号
*/
int sum(int &a,int b){
    int n=a+b;
    a=a+1;
    return n;
}
int main(){
    int x,c=3,d=5;
    //调用sum函数,调用时并不写&号
    x=sum(c,d);
    cout<<"x="<<x<<",c="<<c;
    return 0;
}
 
//指针传递
#include <bits/stdc++.h>
using namespace std;
/*
要接收相应变量的内存中变量的值,需要利用指针,
再接收内存地址的相应变量位置的变量前加"*"号,
运算时同样需要带*号,表示指针所指的那个变量参与运算
*/
int sum(int *a,int b){
    int n=*a+b;
    *a=*a+1;
    return n;
}
int main(){
    int x,c=3,d=5;
    //调用sum函数,要传递c的内存地址,前面加&号
    x=sum(&c,d);
    cout<<"x="<<x<<",c="<<c;
    return 0;
}

  

posted @   fushuxuan1  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示