您得到的错误是因为编译器无法识别nullptr
关键字。这是因为nullptr
在比您使用的版本更高的 Visual Studio 中引入。
有两种方法可以让它在旧版本中工作。一个想法来自 Scott Meyers c++ 一书,他建议创建一个带有nullptr
类似这样的类的标题:
const // It is a const object...
class nullptr_t
{
public:
template<class T>
inline operator T*() const // convertible to any type of null non-member pointer...
{ return 0; }
template<class C, class T>
inline operator T C::*() const // or any type of null member pointer...
{ return 0; }
private:
void operator&() const; // Can't take address of nullptr
} nullptr = {};
这样你只需要根据 msvc 的版本有条件地包含文件
#if _MSC_VER < 1600 //MSVC version <8
#include "nullptr_emulation.h"
#endif
这具有使用相同关键字的优点,并且使升级到新编译器变得相当容易(如果可以,请进行升级)。如果您现在使用较新的编译器进行编译,那么您的自定义代码根本不会被使用,而您只使用 c++ 语言,我觉得这对未来很重要。
如果您不想采用这种方法,则可以使用模仿旧 C 风格方法 ( #define NULL ((void *)0)
) 的方法,您可以在其中创建如下宏NULL
:
#define NULL 0
if(data == NULL){
}
请注意,这与在 C 中发现的并不完全相同NULL
,有关此问题的更多讨论,请参见以下问题:为什么 NULL 指针在 C 和 C++ 中定义不同?
这样做的缺点是您必须更改源代码,而且它不像nullptr
. 所以谨慎使用它,如果你不小心,它可能会引入一些微妙的错误,而正是这些微妙的错误nullptr
首先推动了开发。