关于 C++ 中指针和引用的混淆

Confusion about pointers and references in C++(关于 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;

编译器给了我一个关于 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++ 中指针和引用的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Could I ever want to access the address zero?(我可以想访问地址零吗?)
C++ Access derived class member from base class pointer(C++ 从基类指针访问派生类成员)
Weird Behaviour with const_cast(const_cast 的奇怪行为)
Are pointer variables just integers with some operators or are they quot;symbolicquot;?(指针变量只是带有某些运算符的整数还是“符号?)
Modifying a char *const string(修改 char *const 字符串)
Modifying a const int in C++(修改 C++ 中的 const int)