试图理解通过引用传递C++

Trying to understand passing by reference C++

本文关键字:引用 C++      更新时间:2023-10-16

我了解按值传递和按引用传递之间的基本区别。按值传递意味着将值作为函数参数传递,通过引用传递意味着您只需传递变量。

我不明白的是究竟是如何工作的。这是我的例子。

#include <iostream>
// Initializing Functions
void swap(int &first, int &second);
void write_and_prompt();

int main()
{
int num1 {30};
int num2 {185};
std::cout << "The original value of num1 is: " << num1 << 'n';
std::cout << "The original value of num2 is: " << num2 << 'n';
std::cout << "nSwapping values..." << 'n';
std::cout << "Values have been swapped." << 'n';
// Function for swapping values.
swap(num1, num2);
std::cout << "nThe value of num1 is: " << num1 << 'n';
std::cout << "The value of num2 is: " << num2 << 'n';
// Function that ends program after users input
write_and_prompt();
} // End of main
// Creating Fucntions
void swap(int &first, int &second)
{
int temp = first;
first = second;
second = temp;
}
void write_and_prompt()
{
std::cout << "nPress enter to exit the program." << 'n';
std::cin.get();
}

所以我不明白的是,当我调用函数 swap(num1, num2( 时,我正在传递这两个变量,但在函数的语法中,我有 &first, &second。

我以为我传递的是 num1 和 num2的地址,但后来我认为我需要函数中的指针才能使用它们,而且我会在 num1 和 num2 前面使用 address-of 运算符代替。

无论如何,我试图理解的是为什么使用 address-of 运算符 (&( 使函数采用变量 num1 和 num2。

我以为这个运算符只是给出了变量的地址,或者我可能没有正确理解它。

您是正确的,一元&运算符给出了变量的地址。但是,函数参数中的&不是地址运算符 - 它将该特定参数标记为按引用传递,这与传递指针具有不同的语义。如果要传入指针,可以使用int *first, int *second,就像在函数体中声明指向整数的指针一样。

int &是对int的引用,与地址运算符不同。函数参数是引用,因此无需传递地址或指针。