关于 C++ 中指针和引用的混淆 [英] Confusion about pointers and references in C++

查看:28
本文介绍了关于 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;

编译器给了我一个关于 intint* 错误的错误,这是预期的.尽管我没有使用带有 & 运算符的方法,为什么第一个代码会进行正确的交换?

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::cinstd::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++ 中指针和引用的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆