指標傳遞與 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。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP