指针传递与 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。

更新于: 2019 年 7 月 30 日

3K+ 浏览

开启您的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.