.编两个子函数,分别用指针和引用实现主程序两个交换。
时间: 2024-03-02 18:48:29 浏览: 58
好的,我可以为您编写这两个子函数。
使用指针实现交换:
```c++
#include <iostream>
using namespace std;
void swap_ptr(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap_ptr(&x, &y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
```
使用引用实现交换:
```c++
#include <iostream>
using namespace std;
void swap_ref(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap_ref(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
```
这两个程序的输出是相同的:
```
Before swap: x = 5, y = 10
After swap: x = 10, y = 5
```
阅读全文