我很难理解 w3schools 教程中的这个示例是如何工作的。
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
system("pause");
return 0;
}
我想我理解了第一部分:
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
我基本上引用了调用函数时的 x
和 y
。因此 x 将“指向”firstNum,y 将指向 secondaryNum。它将使用第三个变量作为占位符来执行切换。
但是,在调用函数 swapNums(firstNum, secondaryNum);
后,我不明白该函数及其局部变量如何能够更改 int firstNum 的值= 10;
和 int secondaryNum = 20;
。
我的理解是,函数内的变量是“局部的”,并且所述变量的范围仅在函数本身内扩展。局部变量如何在没有任何 return 语句的情况下更改自己函数之外的其他变量?
最佳答案
试试这个
#include <iostream>
void change_val_by_ref(int &x)
{
x=100
}
void change_val_by_val(int x)
{
x=50;
}
int main()
{
int whatever=0;
std::cout<<"Original value: "<<whatever<<"\n";
change_val_by_ref(whatever);
std::cout<<"After change by ref: "<<whatever<<"\n";
change_val_by_val(whatever);
std::cout<<"After change by val: "<<whatever<<"\n";
}
您将看到的输出是:
0
100
100
让我们看看发生了什么
change_val_by_ref
更改了原始的whatever
,因为 ref “指向”变量。change_val_by_val
没有更改whatever
,因为函数x
的参数刚刚复制了whatever< 的值
,x
发生的任何事情都不会影响whatever
,因为它们不相关。
这就是传递 ref 的要点。
关于c++ - 如何理解 "Pass By Reference Within a Function"w3schools示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69121733/