Confusion about pointers and references in C++(关于 C++ 中指针和引用的混淆)
问题描述
我有一堆这样的代码:
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a;
int b;
a = 7;
b = 5;
swap(a, b);
cout << a << b;
return 0;
}
这段代码按照我真正想要交换 2 个数字的方式执行交换过程,但是当我想要用户提供两个数字时,如下所示;
This code does the swapping process as what I exactly wanted to swap 2 numbers, but when I want two numbers from the user as follows;
int a;
int b;
cin >> a;
cin >> b;
swap(a, b);
cout << a << b;
编译器给了我一个关于 int
到 int*
错误的错误,这是预期的.尽管我没有使用带有 &
运算符的方法,为什么第一个代码会进行正确的交换?
the compiler gives me an error about int
to int*
error which is as expected. Why does the first code do the right swapping although I didn't use the method with &
operator?
推荐答案
在第一个例子中,std::swap
被调用,因为你的using namespace std
.第二个例子和第一个完全一样,所以你可能没有用.
In the first example, std::swap
is called, because of your using namespace std
.
The second example is exactly the same as the first one, so you might have no using.
无论如何,如果您将函数重命名为 my_swap
或类似名称(并更改每次出现的次数),那么第一个代码不应按预期工作.或者,删除 using namespace std
并显式调用 std::cin
和 std::cout
.我会推荐第二个选项.
Anyway, if you rename your function to my_swap
or something like that (and change every occurence), then the first code shouldn't work, as expected. Or, remove the using namespace std
and call std::cin
and std::cout
explicitly. I would recommend the second option.
这篇关于关于 C++ 中指针和引用的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:关于 C++ 中指针和引用的混淆


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01