按引用传递

按引用传递 首页 / 函数式入门教程 / 按引用传递

在"Call by Reference"中,原始值已更改,因为我们传递了参数的引用地址,实际参数和形式参数共享相同的地址空间,因此函数内部值的任何更改都将反映在函数内部和外部。

在C ++中通过引用调用

以下程序显示了按值调用在C++中的工作方式-

#include <iostream> 
using namespace std; 

void learnfk_swap(int *a, int *b) {    
   int temp; 
   temp = *a; 
   *a = *b; 
   *b = temp; 
   cout<<"\n"<<"value of a inside the function: "<<*a; 
   cout<<"\n"<<"value of b inside the function: "<<*b; 
}  
int main() {     
   int a = 50, b = 75;   
   cout<<"\n"<<"value of a before sending to function: "<<a; 
   cout<<"\n"<<"value of b before sending to function: "<<b; 
   learnfk_swap(&a, &b);  //passing value to function 
   cout<<"\n"<<"value of a after sending to function: "<<a; 
   cout<<"\n"<<"value of b after sending to function: "<<b; 
   return 0;   
}

它将产生以下输出-

无涯教程网

value of a before sending to function:  50 
value of b before sending to function:  75 
value of a inside the function:  75 
value of b inside the function: 50 
value of a after sending to function:  75 
value of b after sending to function:  50 

在Python中按引用调用

以下程序显示了按值调用在Python中的工作方式-

def learnfk_swap(a,b): 
   t = a; 
   a = b; 
   b = t; 
   print "value of a inside the function: :",a 
   print "value of b inside the function: ",b 
   return(a,b) 
    
# Now we can call swap function 
a = 50 
b =75 
print "value of a before sending to function: ",a 
print "value of b before sending to function: ",b 
x = learnfk_swap(a,b) 
print "value of a after sending to function: ", x[0] 
print "value of b after sending to function: ",x[1] 

它将产生以下输出-

无涯教程网

value of a before sending to function:  50 
value of b before sending to function:  75 
value of a inside the function:  75 
value of b inside the function:  50 
value of a after sending to function:  75 
value of b after sending to function:  50  

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

接口测试入门课 -〔陈磊〕

分布式协议与算法实战 -〔韩健〕

SRE实战手册 -〔赵成〕

互联网人的英语私教课 -〔陈亦峰〕

Linux内核技术实战课 -〔邵亚方〕

技术领导力实战笔记 2022 -〔TGO 鲲鹏会〕

AI大模型之美 -〔徐文浩〕

徐昊 · AI 时代的软件工程 -〔徐昊〕

好记忆不如烂笔头。留下您的足迹吧 :)