定义a=4,b=5,写3个重载函数swap,分别采用值传递、地址传递,引用传递3种方式,实现a,b值交换,请写出C++代码。
时间: 2024-09-26 11:12:11 浏览: 31
c代码-6.函数调用(参数传递)
在C++中,我们可以分别为值传递、地址传递(即指针传递),以及引用传递编写三个`swap`函数来交换两个变量的值。这里是一个示例:
1. **值传递** (通过临时副本交换):
```cpp
void swapByValue(int a, int b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 4, b = 5;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swapByValue(a, b);
cout << "After swapByValue: a = " << a << ", b = " << b << endl;
return 0;
}
```
2. **地址传递** (通过指针):
```cpp
void swapByPointer(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a = 4, b = 5;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swapByPointer(&a, &b);
cout << "After swapByPointer: a = " << a << ", b = " << b << endl;
return 0;
}
```
3. **引用传递** (直接操作原址):
```cpp
void swapByReference(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = 4, b = 5;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swapByReference(a, b);
cout << "After swapByReference: a = " << a << ", b = " << b << endl;
return 0;
}
```
阅读全文