在C++中理解Null pTR

考虑下面的C++程序,它显示了空问题(需要Null pTR)

null

CPP

// C++ program to demonstrate problem with NULL
#include <bits/stdc++.h>
using namespace std;
// function with integer argument
void fun( int N)   { cout << "fun(int)" ; return ;}
// Overloaded function with char pointer argument
void fun( char * s)  { cout << "fun(char *)" ; return ;}
int main()
{
// Ideally, it should have called fun(char *),
// but it causes compiler error.
fun(NULL);
}


输出:

16:13: error: call of overloaded 'fun(NULL)' is ambiguous     fun(NULL);

以上程序有什么问题? NULL通常定义为(void*)0,允许将NULL转换为整数类型。因此函数调用fun(NULL)变得模棱两可。

CPP

// This program compiles (may produce warning)
#include<stdio.h>
int main()
{
int x = NULL;
}


nullptr如何解决这个问题? 在上面的程序中,如果我们用nullptr替换NULL,我们得到的输出是“fun(char*)”。 nullptr是一个关键字,可以在所有需要NULL的地方使用。与NULL一样,nullptr是隐式可转换的,可以与任何指针类型进行比较。 与NULL不同,它不能隐式转换,也不能与整型进行比较 .

CPP

// This program does NOT compile
#include<stdio.h>
int main()
{
int x = nullptr;
}


输出:

Compiler Error

作为旁注, nullptr可转换为bool。

CPP

// This program compiles
#include<iostream>
using namespace std;
int main()
{
int *ptr = nullptr;
// Below line compiles
if (ptr) { cout << "true" ; }
else { cout << "false" ; }
}


输出:

false

当我们比较两个简单指针时,会出现一些未指明的情况,但是类型为nullptr_t的两个值之间的比较被指定为,comparison by<=和>=返回true,comparison by返回false,并将任何指针类型与nullptr by==和!=如果分别为null或非null,则返回true或false。

C

// C++ program to show comparisons with nullptr
#include <bits/stdc++.h>
using namespace std;
// Driver program to test behavior of nullptr
int main()
{
// creating two variables of nullptr_t type
// i.e., with value equal to nullptr
nullptr_t np1, np2;
// <= and >= comparison always return true
if (np1 >= np2)
cout << "can compare" << endl;
else
cout << "can not compare" << endl;
// Initialize a pointer with value equal to np1
char *x = np1; // same as x = nullptr (or x = NULL
// will also work)
if (x == nullptr)
cout << "x is null" << endl;
else
cout << "x is not null" << endl;
return 0;
}


输出:

can comparex is null

本文由Utkarsh Trivedi撰稿。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享