VIc*_*ean 6 c++ visual-studio-2008 nullptr
我想用Visual Studio 2008 Express编译源代码,但是我收到了这个错误:
Error C2065: 'nullptr' undeclared identifier.
Run Code Online (Sandbox Code Playgroud)
我的代码:
if (Data == nullptr)
{
show("Data is null");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在google上看到我应该升级到Visual Studio 2010,但由于2008年的知识产权,我不想这样做.可以修理或更换吗?
您得到的错误是因为编译器无法识别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 = {};
Run Code Online (Sandbox Code Playgroud)
这样,您只需要根据msvc的版本有条件地包含该文件
#if _MSC_VER < 1600 //MSVC version <8
#include "nullptr_emulation.h"
#endif
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以使用相同的关键字,并且可以更轻松地升级到新的编译器(如果可以,请进行升级).如果您现在使用较新的编译器进行编译,那么您的自定义代码根本不会被使用,而您只使用c ++语言,我觉得这很重要.
如果你不想采用这种方法,你可以使用模仿旧C风格方法的东西(#define NULL ((void *)0)),你可以NULL像这样制作一个宏:
#define NULL 0
if(data == NULL){
}
Run Code Online (Sandbox Code Playgroud)
请注意,这与NULLC中的不完全相同,有关更多讨论,请参阅此问题:为什么在C和C++中对NULL指针进行了不同的定义?
这样做的缺点是你必须改变源代码,它不像类似安全nullptr.所以谨慎使用它,如果你不小心它会引入一些微妙的错误,而这些微妙的错误首先促使了它们的发展nullptr.
| 归档时间: |
|
| 查看次数: |
24783 次 |
| 最近记录: |