ตัวชี้สามารถรับพารามิเตอร์ null ได้ในขณะที่การอ้างอิงไม่สามารถทำได้ คุณสามารถใช้ตัวชี้ได้ก็ต่อเมื่อต้องการส่ง “ไม่มีวัตถุ”
การผ่านตัวชี้อย่างชัดเจนทำให้เราเห็นว่าวัตถุนั้นผ่านโดยการอ้างอิงหรือค่าที่ไซต์การโทรหรือไม่
นี่เป็นตัวอย่างง่ายๆ ของการส่งผ่านตัวชี้และการส่งโดยการอ้างอิง -
ผ่านตัวชี้
ตัวอย่าง
#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