试图理解通过引用传递C++
Trying to understand passing by reference C++
我了解按值传递和按引用传递之间的基本区别。按值传递意味着将值作为函数参数传递,通过引用传递意味着您只需传递变量。
我不明白的是究竟是如何工作的。这是我的例子。
#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的引用,与地址运算符不同。函数参数是引用,因此无需传递地址或指针。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?