在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
热门推荐
10 周末愉快祝福语高级简短
11 新大学开学祝福语简短
12 祝福语献给老人的话简短
13 孩子转学离群祝福语简短
14 简短祝福语中考女孩的话
15 送给客户的祝福语 简短
16 生日祝福语简短蛋糕上
17 鱼的内涵简短祝福语
18 新人结婚简短祝福语大全