我实际上在想这个程序应该抛出一个编译错误(因为我正在将值传递给交换方法而不是 &a,&b)但我很震惊地看到它成功执行了。所以,我发布这个是为了知道它是如何/为什么没有任何错误地执行的。
#include <iostream>
using namespace std;
void swap(int* x, int* y)
{
int z = *x;
*x = *y;
*y = z;
}
int main()
{
int a = 45, b = 35;
cout << "Before Swap\n";
cout << "a = " << a << " b = " << b << "\n";
swap(a, b);
cout << "After Swap with pass by pointer\n";
cout << "a = " << a << " b = " << b << "\n";
}