NULL与nullptr

nullptr在C++11被引入到C++,解决了NULL在C++代码中存在的二义性问题。在C++中是这么定义NULL的

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

在C中是一个void*的指针,如果将NULL作为空指针进行使用是没有问题的,但是在C++重载函数代码中会存在编译报错,

#include <iostream>
using namespace std;

void Print(int n){
	cout<<n<<endl;
}

void Print(int* p){
	cout<<*p<<endl;
}

int main()
{
   Print(NULL);
   return 0;
}

运行上面代码,会在编译期报错,原因是编译器无法确定你想要执行哪一个函数,下面是错误提示

main.cpp: In function ‘int main()’:
main.cpp:14:14: error: call of overloaded ‘Print(NULL)’ is ambiguous
   14 |    Print(NULL);
      |              ^
main.cpp:4:6: note: candidate: ‘void Print(int)’
    4 | void Print(int n){
      |      ^~~~~
main.cpp:8:6: note: candidate: ‘void Print(int*)’
    8 | void Print(int* p){
      |      ^~~~~

因此在C++中应该用nullptr来代替NULL,作为指针的初始化。

posted @ 2022-12-08 20:54  我一直站在悬崖上  阅读(51)  评论(0)    收藏  举报