各位大神,用C++怎么写啊?

编写程序,创建3个函数分别采用按值转递、地址转递和引用转递方式将main()函数中给出的两个数进行交换。
小强129619
浏览 1196回答 3
3回答

书之诗ae

同学,不能用值传递啊。值传递是单向的实参->形参,参数的值只能传入,不能传出,建议用指针传递,个人建议&传递。望采纳!

书之诗ae

#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;}
打开App,查看更多内容
随时随地看视频慕课网APP