#include <iostream>
using namespace std;
void swap1(int, int);
void swap2(int*, int*);
void swap3(int&, int&);
void show(const int&, const int&);
void swap1(int num1, int num2)
{
int temp;
temp = num1;
num1 = num2;
num2 = temp;
}
void swap2(int* p1, int* p2)
{
int temp;
temp = *p1; //交换的是根据地址指向的值
*p1 = *p2;
*p2 = temp;
}
void swap3(int& ref1, int& ref2)
{
// 引用,
// 可以更加简便书写代码,可以直接传递某个对象,而不是把对象复制一份
int temp;
temp = ref1;
ref1 = ref2;
ref2 = temp;
}
void show(const int& num1, const int& num2)
{
// 使用const,不希望别人随意修改我们的参数
cout << "执行swap后:" << num1 << '\t' << num2 << endl;
}
int main()
{
int num1 = 10, num2 = 5;
//* 把值复制了一份进去,原本的值未改变*/
swap1(num1, num2);
show(num1, num2);
// cout << "执行swap1后:" << num1 << '\t' << num2 << endl;
swap2(&num1, &num2); // 指针的方式
show(num1, num2);
// cout << "执行swap2后:"<< num1 << '\t' << num2 << endl;
swap3(num1, num2); // 引用的方式,效果一样,也能交换,引用是指针的高级实现
show(num1, num2);
// cout << "执行swap3后:"<< num1 << '\t' << num2 << endl;
}
执行swap后:10 5
执行swap后:5 10
执行swap后:10 5