为什么没有声明 NULL?

当我尝试编译这段代码时,我遇到了这个结构构造函数的问题:

typedef struct Node
{
Node( int data ) //
{
this->data = data;
previous = NULL; // Compiler indicates here
next = NULL;
}


int data;
Node* previous;
Node* next;
} NODE;

当我来的时候,这个错误发生了:

\linkedlist\linkedlist.h||In constructor `Node::Node(int)':|
\linkedlist\linkedlist.h|9|error: `NULL' was not declared in this scope|
||=== Build finished: 1 errors, 0 warnings ===|

最后一个问题是 struct,但是它在 main.cpp 中工作得很好,这次是在头文件中,给我带来了这个问题。我使用 Code: : 块来编译这段代码

220004 次浏览

Are you including "stdlib.h" or "cstdlib" in this file? NULL is defined in stdlib.h/cstdlib

#include <stdlib.h>

or

#include <cstdlib>  // This is preferrable for c++

NULL is not a built-in constant in the C or C++ languages. In fact, in C++ it's more or less obsolete, just use a plain literal 0 instead, the compiler will do the right thing depending on the context.

In newer C++ (C++11 and higher), use nullptr (as pointed out in a comment, thanks).

Otherwise, add

#include <stddef.h>

to get the NULL definition.

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

Don't use NULL, C++ allows you to use the unadorned 0 instead:

previous = 0;
next = 0;

And, as at C++11, you generally shouldn't be using either NULL or 0 since it provides you with nullptr of type std::nullptr_t, which is better suited to the task.

Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

There are problems with using 0 (and hence NULL). For example:

void f(int);
void f(void*);


f(0); // Ambiguous. Calls f(int).

The next version of C++ (C++0x) includes nullptr to fix this.

f(nullptr); // Calls f(void*).