c++中的函数按值调用和按引用调用

functions in c++ call by value and call by reference

本文关键字:引用 调用 值调用 c++ 函数      更新时间:2023-10-16

以下代码是在两种方法中调用函数的示例请告诉我按价值调用和按参考调用之间的主要区别或含义1.按值调用。2.参照调用下面的代码说明了按值调用方法。

我在评论中详细说明了我的疑虑

#include<iostream>
int main(){
void change(int);//why function prototype is before function definition and what is 
int orig=10;//meaning of argument int, it did not defined any variable of type int
cout<<"The original value is: "<<orig<<"n";
change(orig);//what is the meaning of this piece of code
cout<<"Value after change() is over:"<<orig<<"n";
return 0;
};
void change(int orig){
orig=20;
cout<<"Value of orig in function change() is:"<<orig<<"n";
return;
}

在书中我读到函数定义应该先于函数原型。

按值调用生成参数的副本,并将其放入局部变量中供函数使用,因此,如果函数更改了局部变量的值,则参数本身不会更改。通过引用调用将参数的引用传递给函数,而不是副本,因此,如果函数更改了参数的值,则参数本身也会更改。

函数原型void change(int);告诉编译器存在一个名为change的函数,该函数接受类型为int的单个参数并返回void(即不返回)。它是按值调用的,因为参数中没有&。在代码的后面有一行change(orig);,它实际调用具有int类型的参数orig的函数。由于函数原型是在此函数调用之前声明的,因此编译器将其识别为函数。

看看这个程序的输出:

#include<iostream>
using namespace std;
int main(){
  void change(int);
  void change2(int&);
  int x = 10;
  cout<<"The original value of x is: "<< x <<"n";
  change(x); // call change(), which uses call by value
  cout<<"Value of x after change() is over: "<< x <<"n";
  change2(x); // call change2(), which uses call by reference
  cout<<"Value of x after change2() is over: "<< x <<"n";
  return 0;
};
void change(int orig){
    cout<<"Value of orig in function change() at beginning is: "<<orig<<"n";
    orig=20;
    cout<<"Value of orig in function change() at end is: "<<orig<<"n";
  return;
}
void change2(int &orig){
    cout<<"Value of orig in function change2() at beginning is: "<<orig<<"n";
    orig=20;
    cout<<"Value of orig in function change2() at end is: "<<orig<<"n";
  return;
}

为了避免名称混淆,我将main()中的int orig更改为int x,并添加了使用引用调用的change2()

主要区别在于"通过引用传递"传递对象的引用,而不是对象的副本。因此,被调用的函数可以访问对象所在的同一内存位置,并在需要时对其进行修改。相反,当传递对象的副本时,会对复制的对象进行修改,而不是对原始对象进行修改。

您可以在代码中添加以下内容并查看差异:

#include<iostream>
void change(int);
void change_ref(int&);
int main(){
    int orig=10;//meaning of argument int, it did not defined any variable of type int
    cout<<"The original value is: "<<orig<<"n";
    change_ref(orig);//what is the meaning of this piece of code
    cout<<"Value after change() is over:"<<orig<<"n";
    return 0;
};
void change_ref(int& orig){
    orig=20;
    cout<<"Value of orig in function change() is:"<<orig<<"n";
    return;
}

传递值意味着,如果您在函数内部更改值,那么它将不会对函数外部产生影响(当函数返回时)。其中as pass-by-reference意味着,如果函数中的值发生了更改,它也将在外部发生更改(当函数返回时)。

通过引用传递和通过值传递之间的区别的一个很好的例子是将数组传递给函数。它可以通过指针或引用传递。这里的链接就是一个很好的例子。