在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP