我正在尝试使用 Visual Studio 2008 Express 编译源代码,但出现此错误:
Error C2065: 'nullptr' undeclared identifier.
我的代码:
if (Data == nullptr) {
show("Data is null");
return 0;
}
我在 Google 上读到我应该升级到 Visual Studio 2010,但由于 Visual Studio 2008 中的 IntelliSense,我不想这样做。这可以修复或更换吗?
最佳答案
您遇到的错误是因为编译器无法识别 nullptr
关键字。这是因为 nullptr
是在比您正在使用的更高版本的 visual studio 中引入的。
您可以通过两种方式让它在旧版本中运行。一个想法来自 Scott Meyers c++ 书,他建议创建一个带有模拟 nullptr
类的 header ,如下所示:
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
不完全相同,有关更多讨论,请参阅以下问题:Why are NULL pointers defined differently in C and C++?
这样做的缺点是您必须更改源代码,而且它不像 nullptr
那样是类型安全的。所以请谨慎使用它,如果您不小心,它可能会引入一些细微的错误,正是这些细微的错误首先激发了 nullptr
的开发。
关于c++ - 编译错误 'nullptr' 未声明的标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433436/