对于C和C++程序员来说,一定不会对NULL感到陌生。但是C和C++中的NULL却不等价。NULL表示指针不指向任何对象。
NULL是一个宏定义
在C中将NULL定义为void*指针值为0
#define NULL (void*)0
在C++中,NULL被定义为常数0
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
考虑下面的程序
#include
#include
using namespace std; void f(int i) { cout << "f(int)" << endl; } void f(void* ptr) { cout << "f(void*)" << endl; } int main() { f(NULL); return 0; }
输出结果:

<??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+bnVsbHB0csihtPrBy9PQtO3O88fjz/K1xE5VTEwsbnVsbHB0cr/J0tSxu8DtveLOqta4z/JOVUxMtcTWuNXrPC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">#include
#include
using namespace std; void f(int i) { cout << "f(int)" << endl; } void f(void* ptr) { cout << "f(void*)" << endl; } int main() { //f(NULL); f(0); //输出为f(int) f(nullptr); //输出为f(void*) return 0; }
nullptr适用于所有指针类别,包括函数指针和成员指针
const char *pc = str.c_str();
if (pc != nullptr)
cout << pc << endl;
void (*func)() = nullptr;
不能将nullptr赋值给整形
int i1 = nullptr; //error
if (i1 == nullptr){} //error
if (nullptr){} //error
nullptr = 0; //error