在 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

更新於: 2019 年 7 月 30 日

457 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.