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

การส่งผ่านแบบ Pointer เทียบกับการส่งผ่านแบบ Reference ใน C++


นี่คือตัวอย่างง่ายๆ ของการส่งผ่านแบบ Pointer และการส่งผ่านแบบ Reference -

การส่งผ่านแบบ 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

การส่งผ่านแบบ 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

ดังนั้น หากเราส่งพารามิเตอร์ให้ฟังก์ชันไม่ว่าจะเป็นแบบ Pass by Pointer หรือ Pass by Reference จะให้ผลลัพธ์เดียวกัน ความแตกต่างคือ Reference ใช้เพื่ออ้างถึงตัวแปรที่มีอยู่ด้วยชื่ออื่น ในขณะที่ Pointer ใช้เก็บที่อยู่ของตัวแปร การใช้ Reference ปลอดภัยกว่าเพราะไม่สามารถเป็น NULL ได้