C++ 利用指针以及引用交换两个数

注意指针交换的是指针所指向的数,不是指针本身,这个要特别注意

#include <iostream> 
using namespace std;

void swap(int& x, int& y);          // 两个数的交换引用
void swap(int* x, int* y);          // 两个数的交换指针所指向的值


int main()
{
	int a, b;
	cin >> a >> b;
	swap(&a, &b);
	cout << a << " " << b << endl;

}

void swap(int* x, int* y)
{
	int temp;
	temp = *x;
	*x = *y;
	*y = temp;
}

void swap(int& x, int& y)
{
	int temp;
    temp = x;
	x = y;
	y = temp;
}

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/82898720