C++特性nullptr

nullptr:C++不允许直接将void*隐式转换到其他类型,没有隐式转换的C++只好
将NULL定义为0,但会出现新的问题,C++中的重载特性会发生混乱
为了区分NULL、0从而引入的关键字,nullptr的类型为nullptr_t
能够隐式的转换为任何指针或成员指针类型,也能进行相等或不相等进行比较;

#include <iostream>


void test1()
{
    char *ptr = NULL;
    // NULL 不等于0
    if (std::is_same<decltype(NULL), decltype(0)>::value)
    {
        std::cout<<"NULL == 0"<<std::endl;
    }
    // NULL不等于(void*)0
    if (std::is_same<decltype(NULL), decltype((void*)0)>::value)
    {
        std::cout<<"NULL == (void*)0"<<std::endl;
    }

    // NULL不等于nullptr
    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(NULL);//报错,C++没有隐式类型转换,将NULL定义为0,但是重载函数都符合
    fool(0);//  调用fool(int i);
    fool(nullptr);//    调用 fool(char *ptr);
}
int main()
{
    test1();
    test2();
    return 0;
}

版权声明:本文为CodeHouse原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。