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++ 中指针和引用的混淆


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01