在C ++中通过指针传递Vs通过引用传递
这些是通过指针传递和通过引用传递的简单示例-
通过指针
#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。