C++ 中的指针参数传递和引⽤参数传递
时间: 2023-07-16 11:12:14 浏览: 84
在 C++ 中,函数参数传递通常有两种方式:指针参数传递和引用参数传递。
指针参数传递是将参数的地址作为函数参数传递。在函数内部,可以通过指针解引用(`*`)操作符来访问该参数的值。指针参数传递的优点是可以修改参数的值,但需要注意的是,指针参数传递可能会导致空指针异常和野指针问题。
引用参数传递是将参数的别名作为函数参数传递。在函数内部,可以直接使用该参数的别名来访问参数的值。与指针参数传递相比,引用参数传递的优点是更加简洁明了,而且不会出现空指针和野指针问题。
以下是一个示例代码,演示了指针参数传递和引用参数传递的区别:
```c++
#include <iostream>
using namespace std;
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
void swap(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 1, b = 2;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swap(&a, &b);
cout << "After swap using pointer parameters: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap using reference parameters: a = " << a << ", b = " << b << endl;
return 0;
}
```
输出结果为:
```
Before swap: a = 1, b = 2
After swap using pointer parameters: a = 2, b = 1
After swap using reference parameters: a = 1, b = 2
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)