3 回答
TA贡献5条经验 获得超3个赞
#include <iostream>
using namespace std;
//按值传递
void swap1(int &x, int &y)//值传递是单向传递,实参->形参,参数的值只能传入,不能传出,建议用指针传递,个人建议&传递。
{
int temp;
temp = x;
x = y;
y = temp;
}
//按址传递
void swap2(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
//按引用传递
void swap3(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}
int main()
{
int a = 1, b = 2;
int c = 3, d = 4;
int e = 5, f = 6;
cout << "交换前:a=" << a << ",b=" << b << endl;
cout << "按值传递交换a和b。\n";
swap1(a, b);
cout << "交换后:a=" << a << ",b=" << b << endl;
cout << "\n";
cout << "交换前:c=" << c << ",d=" << d << endl;
cout << "按址传递交换c和d。\n";
swap2(&c, &d);
cout << "交换后:c=" << c << ",d=" << d << endl;
cout << "\n";
cout << "交换前:e=" << e << ",f=" << f << endl;
cout << "按引用传递交换e和f。\n";
swap3(e, f);
cout << "交换后:e=" << e << ",f=" << f << endl;
return 0;
}
- 3 回答
- 0 关注
- 1226 浏览
添加回答
举报