<span style="font-size:18px;">#include <iostream> using namespace std; void show(int num) { cout << "int " << endl; } void show(int* num)(本程序测试是用int* 可以其他类型,最终是 std::nullptr_t类型转化过来) { cout << "int* " << endl; } int main() { cout << "NULL\t"; show(NULL); cout << "nullptr\t";show(nullptr); cout <<"NULL\t"<< typeid(NULL).name() << endl; cout << "nullptr\t" << typeid(nullptr).name() << endl; //cin.get(); return 0; }</span>
结果
从结果上来看,NULL本身是一个int类型, nullptr是一个指针类型(nullptr_t)
解释:
1、NULL:
#include<stdlib.h>中对NULL预处理:
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
在c语言环境下,由于C语言是一种弱类型语言并且由于不存在函数重载等问题,直接将NULL定义为一个void*的指针就可以完美的解决一切问题。但是在c++环境下情况就变得复杂起来,首先我们不能写这样码 int* fp = (void*)0;(因为c++是强类型语言) 将void*直接赋值给一个指针是不合法的,编译器会报错。 我们只能这样写代码int* fp = (int*)0;or int* fp = 0;
所以在c++下面,NULL就被直接定义为一个整型 0。 在大多数情况下这并不会产生什么问题,但是万一有重载或者模板推导的时候,编译器就无法给出正确结果了。比如下面的情形:
void process(int* target, void* data);
process( target, NULL); // error 函数类型是void* ,但是我们绑定的是一个整型 0
2、nullptr:
上述程序看来,nullptr是一个nullptr_t类型,这个类型在c++下可以隐式的强制转化成任意的指针类型。