C++ 错误:未在此范围内声明“NULL”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/462165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
error: ‘NULL’ was not declared in this scope
提问by Hymanhab
I get this message when compiling C++ on gcc 4.3
在 gcc 4.3 上编译 C++ 时收到此消息
error: ‘NULL' was not declared in this scope
It appears and disappears and I don't know why. Why?
它出现又消失,我不知道为什么。为什么?
Thanks.
谢谢。
回答by Johannes Schaub - litb
NULL
is not a keyword. It's an identifier defined in some standard headers. You can include
NULL
不是关键字。它是一些标准头文件中定义的标识符。你可以包括
#include <cstddef>
To have it in scope, including some other basics, like std::size_t
.
将其纳入范围,包括其他一些基础知识,例如std::size_t
.
回答by Seppo Enarvi
GCC is taking steps towards C++11, which is probably why you now need to include cstddefin order to use the NULLconstant. The preferred way in C++11 is to use the new nullptrkeyword, which is implemented in GCC since version 4.6. nullptris not implicitly convertible to integral types, so it can be used to disambiguate a call to a function which has been overloaded for both pointer and integral types:
GCC 正在朝着 C++11 迈进,这可能就是您现在需要包含cstddef以使用NULL常量的原因。C++11 中的首选方法是使用新的nullptr关键字,该关键字从 4.6 版开始在 GCC 中实现。nullptr不能隐式转换为整数类型,因此它可用于消除对已为指针和整数类型重载的函数的调用的歧义:
void f(int x);
void f(void * ptr);
f(0); // Passes int 0.
f(nullptr); // Passes void * 0.
回答by David Thornley
NULL
isn't a keyword; it's a macro substitution for 0, and comes in stddef.h
or cstddef
, I believe. You haven't #included
an appropriate header file, so g++ sees NULL
as a regular variable name, and you haven't declared it.
NULL
不是关键字;它是 0 的宏替换,我相信它出现在stddef.h
or 中cstddef
。您没有#included
合适的头文件,因此 g++ 将其NULL
视为常规变量名,而您尚未声明它。
回答by Leonardo Raele
To complete the other answers: If you are using C++11, use nullptr
, which is a keyword that means a void pointer pointing to null. (instead of NULL
, which is not a pointer type)
完成其他答案:如果您使用的是 C++11,请使用nullptr
,这是一个关键字,表示指向 null 的空指针。(而不是NULL
,它不是指针类型)
回答by Derzu
You can declare the macro NULL. Add that after your #includes:
您可以将宏声明为 NULL。在 #includes 之后添加:
#define NULL 0
or
或者
#ifndef NULL
#define NULL 0
#endif
No ";" at the end of the instructions...
不 ”;” 在说明的最后...
回答by Owl
NULL can also be found in:
NULL 也可以在以下位置找到:
#include <string.h>
String.h will pull in the NULL from somewhere else.
String.h 将从其他地方拉入 NULL。