ในส่วนนี้เราจะเห็นค่า nullptr ใน C++ nullptr หมายถึงตัวอักษรตัวชี้ เป็นค่า prvalue ของประเภท std::nullptr_t มีคุณสมบัติการแปลงโดยนัยจากค่า nullptr เป็นค่าตัวชี้ null ของตัวชี้ประเภทใด ๆ และตัวชี้ใด ๆ ไปยังประเภทสมาชิก ให้เราดูโปรแกรมหนึ่งเพื่อทำความเข้าใจแนวคิดนี้
ตัวอย่าง
#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
cout << "calling function my_func(char *)";
}
int main() {
my_func(NULL); //it will call my_func(char *), but will generate compiler error
} ผลลัพธ์
[Error] call of overloaded 'my_func(NULL)' is ambiguous [Note] candidates are: [Note] int my_func(int) [Note] int my_func(char*)
ดังนั้นปัญหาในโปรแกรมข้างต้นคืออะไร? โดยทั่วไปค่า NULL ถูกกำหนดเป็น (เป็นโมฆะ*)0 เราได้รับอนุญาตให้แปลง NULL เป็นประเภทอินทิกรัล ดังนั้นการเรียกฟังก์ชันของ my_func(NULL) จึงไม่ชัดเจน
หากเราใช้ nullptr แทน NULL เราจะได้ผลลัพธ์ดังรูปด้านล่าง -
ตัวอย่าง
#include<iostream>
using namespace std;
int my_func(int N){ //function with integer type parameter
cout << "Calling function my_func(int)";
}
int my_func(char* str) { //overloaded function with char* type parameter
cout << "calling function my_func(char *)";
}
int main() {
my_func(nullptr); //it will call my_func(char *), but will generate compiler error
} ผลลัพธ์
calling function my_func(char *)
เราสามารถใช้ nullptr ได้ทุกที่ที่คาดว่าจะเป็น NULL เช่นเดียวกับค่า NULL ค่า nullptr สามารถแปลงเป็นพอยน์เตอร์ประเภทใดก็ได้ แต่สิ่งนี้ไม่สามารถแปลงเป็นอินทิกรัลได้โดยปริยาย เช่น NULL