[英]Swap Function - pointers - confusion
注意,在代碼中我沒有使用指針,但是我有一些概念,如果我將使用此函數,則在代碼塊完成時該值將恢復為正常。
但是代碼正在編譯我實際上將通過指針得到的答案。
如果我有關於指針的犯規概念,我很困惑,我需要幫助。
void swap(int i, int j) {
int temp = i;
i = j;
j = temp;
}
int main() {
int a = 110;
int b = 786;
cout << "Before swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
swap(a,b);
cout << "\nAfter swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
swap(a, b);
cout << "\nAnd back again swapping the value" << endl;
cout << "'a' stores the value : " << a << endl;
cout << "'b' stores the value : " << b << endl;
return 0;
}
似乎您所包含的iostream
標頭還包括utility
標頭。 然后您將std::swap
的定義提取到程序中。
由於您(未顯示,但可能)已經using namesapce std;
在您的代碼中,用於swap
的重載集包含兩個重載。 並且根據過載解決規則,將調用正確的1過載。
1在這種情況下,對於正確的定義
如果要使用指針進行交換,則應傳遞指針:
void swap(int *a, int*b)
{
int temp = *a;
*a = *b;
*b = temp;
}
正如另一個用戶指出的那樣,通過引用傳遞是另一種選擇。
PS:您的查詢與功能指針無關,因此我將從您的查詢中刪除功能指針標記。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.