方法一、使用引用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { void swap(int &, int &); int i = 3, j = 5; swap(i, j); cout << i << " " << j << endl; return 0; } void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } |
方法二、使用指针:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #include <iostream> using namespace std; int main() { void swap(int *, int *); int i = 3, j = 5; swap(&i, &j); cout << i << " " << j << endl; return 0; } void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } |