在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。
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短