(2)用c++方法,输入任意两个整数,编一个函数完成两个整数交换,形参分别采用变量、指针、引用,在主函数里观察三种形参的区别。
时间: 2024-10-16 22:19:11 浏览: 33
在 C++ 中,我们可以使用三个不同的形式来交换两个整数:通过普通变量、指向变量的指针以及使用引用。以下是各自的实现:
1. **通过变量**:
```cpp
void swapByVariable(int a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int num1 = 5, num2 = 10;
std::cout << "Before swap: num1 = " << num1 << ", num2 = " << num2 << std::endl;
swapByVariable(num1, num2);
std::cout << "After swap by variable: num1 = " << num1 << ", num2 = " << num2 << std::endl;
return 0;
}
```
这里,我们直接修改了 `num1` 和 `num2` 的值。
2. **通过指针**:
```cpp
void swapByPointer(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int num1 = 5, num2 = 10;
std::cout << "Before swap: num1 = " << num1 << ", num2 = " << num2 << std::endl;
swapByPointer(&num1, &num2);
std::cout << "After swap by pointer: num1 = " << num1 << ", num2 = " << num2 << std::endl;
return 0;
}
```
在这里,我们通过指针间接访问并交换了数值。
3. **通过引用**:
```cpp
void swapByReference(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int num1 = 5, num2 = 10;
std::cout << "Before swap: num1 = " << num1 << ", num2 = " << num2 << std::endl;
swapByReference(num1, num2);
std::cout << "After swap by reference: num1 = " << num1 << ", num2 = " << num2 << std::endl;
return 0;
}
```
引用操作同样改变了原始变量的值,无需解引用。
阅读全文