定义一个函数后,我们需要在其中传递参数以获得所需的输出,大多数编程语言支持按值调用(call by value)和按引用(call by reference)调用方法,以将参数传递给函数。
在本章中,我们将学习"call by value"在面向对象的编程语言(如C++)和函数式编程语言(如Python)中的工作。
在"call by value "方法中,原始值无法更改,当我们将参数传递给函数时,它由函数参数本地存储在堆栈存储器中。因此仅在函数内部更改值,并且不会在函数外部产生影响。
以下程序显示了按值调用在C ++中的工作方式-
#include <iostream> using namespace std; void learnfk_swap(int a, int b) { int temp; temp = a; a = b; b = temp; cout<<"\n"<<"函数内部 a 的值: "<<a; cout<<"\n"<<"函数内部 b 的值: "<<b; } int main() { int a = 50, b = 70; cout<<"传递前 a 值: "<<a; cout<<"\n"<<"传递前 b 的值: "<<b;
learnfk_swap(a, b); //参数传递 cout<<"\n"<<"传递后 a 值: "<<a;
cout<<"\n"<<"传递后 b 值: "<<b;
return 0; }
它将产生以下输出-
传递前 a 值: 50 传递前 b 值: 70 函数内部 a 的值: 70 函数内部 b 的值: 50
传递后 a 值: 50 传递后 b 值: 70
以下程序显示了按值调用在Python中的工作方式-
来源:LearnFk无涯教程网
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 # Now we can call the swap function a = 50 b = 75 print "value of a before sending to function: ",a print "value of b before sending to function: ",b learnfk_swap(a,b) print "value of a after sending to function: ", a print "value of b after sending to function: ",b
它将产生以下输出-
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: 50 value of b after sending to function: 75
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)