C++ 中的 nullptr 究竟是什麼?


在本節中,我們將看到 C++ 中的 nullptr。nullptr 表示指標字面量。它是 std::nullptr_t 型別的 prvalue。它具有從 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 通常定義為 (void*)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 *)

我們可以在預期 NULL 的所有地方使用 nullptr。像 NULL 一樣,nullptr 也可以轉換為任何指標型別。但它無法像 NULL 那樣隱式轉換為整數型別。

更新時間: 30-Jul-2019

222 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告