/* define null
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
#include <iostream>
*/
- nullptr:C++不允许直接将void*隐式转换到其他类型,没有隐式转换的C++只好
将NULL定义为0,但会出现新的问题,C++中的重载特性会发生混乱
为了区分NULL、0从而引入的关键字,nullptr的类型为nullptr_t
能够隐式的转换为任何指针或成员指针类型,也能进行相等或不相等进行比较;
void test1()
{
char *ptr = NULL;
if (std::is_same<decltype(NULL), decltype(0)>::value)
{
std::cout<<"NULL == 0"<<std::endl;
}
if (std::is_same<decltype(NULL), decltype((void*)0)>::value)
{
std::cout<<"NULL == (void*)0"<<std::endl;
}
if (std::is_same<decltype(NULL), decltype(nullptr)>::value)
{
std::cout<<"NULL == nullptr"<<std::endl;
}
}
void fool(char *ptr)
{
std::cout<<"char* ptr"<<std::endl;
}
void fool(int i)
{
std::cout<<"int i"<<std::endl;
}
void test2()
{
fool(0);
fool(nullptr);
}
int main()
{
test1();
test2();
return 0;
}