問題描述
我有一堆這樣的代碼:
#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++ 中指針和引用的混淆的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!