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

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

编译器给我一个关于整数到*整数错误的错误,这是预期的.尽管我没有在&运算符中使用该方法,但是为什么第一个代码可以正确地进行交换?

The compiler gives me an error about integer to *integer error which is as expected. Why does the first code do the right swapping although I didn't use the method with & operator?

推荐答案

在第一个示例中,由于您的using namespace std而调用std::swap. 第二个示例与第一个示例完全相同,因此您可能没有用.

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天全站免登陆