指针传递与 C++ 中的引用传递
以下是通过指针传递和通过引用传递的简单示例 -
通过指针传递
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int c = *a;
*a= *b;
*b = c;
}
int main() {
int m = 7, n = 6;
cout << "Before Swap\n";
cout << "m = " << m << " n = " << n << "\n";
swap(&m, &n);
cout << "After Swap by pass by pointer\n";
cout << "m = " << m << " n = " << n << "\n";
}输出
Before Swap m = 7 n = 6 After Swap by pass by pointer m = 6 n = 7
通过引用传递
#include <iostream>
using namespace std;
void swap(int& a, int& b) {
int c = a;
a= b;
b = c;
}
int main() {
int m =7, n = 6;
cout << "Before Swap\n";
cout << "m = " << m << " n = " << n << "\n";
swap(m, n);
cout << "After Swap by pass by reference\n";
cout << "m = " << m << " n = " << n << "\n";
}输出
Before Swap m = 7 n = 6 After Swap by pass by reference m = 6 n = 7
因此,如果通过指针传递或通过引用传递参数给函数,它将产生相同的结果。唯一的区别是引用用于引用以其他名称存在的变量,而指针用于存储变量的地址。使用引用是安全的,因为它不能为 NULL。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP