nullptr和NUll的区别

nullptr和NULL

 nullptr可以被转换成任意其他的指针类型;而NULL在cpp种被宏定义为0,在遇到重载时可能会出现问题并且在cpp种不允许被转换.

 void fun(int a){

 cout<< "int"<<endl;

}

 void fun (char* a){

 cout<<"char *"<<endl;

}

Int main(){

 fun(0)

}

 会调用参数为int的函数,但是0也表示NULL空指针

 在cpp中NULL的本质就是宏定义0。只有在cpp中才会定义宏_cplusplus。也就是说如果源代码是c++程序NULL就是0,如果是C程序 NULL表示(void*)0。

#ifndef NULL
    #ifdef _cplusplus
        #define NULL 0
    #else
        #define NULL((void*)0)
    #endif
#endif

由于C++中,void*类型无法隐式转换为其他类型的指针,此时使用0代替((void*)0),用于解决空指针的问题。这个0(0x0000 0000)表示的就是虚拟地址空间中的0地址,这块地址是只读的。

 c语言:

#include<stdio.h>
int main(){
    int*a = (void*)0;//正确可以使用
}

cpp:

#include<iostream>
using namespace std;

int main(){
    //以下均报错
    int *a = (void*)0;
    char *c = (void*)0;
}

猜你喜欢

转载自blog.csdn.net/four_two_six_/article/details/130804898