Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ประโยชน์ของการส่งผ่าน Pointer เทียบกับ Reference ใน C++

Pointer สามารถรับพารามิเตอร์ null ได้ ในขณะที่ reference ไม่สามารถ คุณสามารถใช้ pointer ได้ก็ต่อเมื่อต้องการส่ง "ไม่มีออบเจ็กต์"

การส่งผ่าน pointer แบบชัดเจน (explicitly) ช่วยให้เห็นว่าออบเจ็กต์ถูกส่งโดย reference หรือ value ที่จุดเรียก (call site)

ตัวอย่างง่ายๆ ของการส่งโดย pointer และ reference:

Passing by Pointer

ตัวอย่างโค้ด

#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

Passing by Reference

ตัวอย่างโค้ด

#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