0,NULL和nullpter

#include <iostream>
using namespace std;
void f(int)
{
    cout<<"f(int)"<<endl;
}

void f(bool)
{
    cout<<"f(bool)"<<endl;
}

void f(void*)
{
    cout<<"f(void*)"<<endl;
}

int main()
{
    f(0);
    f(NULL);
    f(nullptr);

    return 0;
}

在C++中:

1. 0首先会被视为int,所以这里调用f(int)。

2. 对于NULL,C++首先视其为广义整形,如果被定义为普通的0,那么调用f(int),如果是0L,由于long->void* ,long->int,long->void*都是合法的,所以编译会出错。

3. 对于nullptr,不属于广义整型,也不属于普通意义上的指针,它可以隐式转化为任何的的原始指针类型,故可以将其理解为一个可以指向任何类型的指针。

 

比如:

 

 使用0和f比较,一时不能够确定是广义整型还是指针类型,而nullpter则只会被认为是指针类型,故不会产生产生二义性。

 

posted @ 2022-01-23 10:40  sunshine_gzw  阅读(92)  评论(0编辑  收藏  举报