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之类的整数类型。
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短