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 @   我一直站在悬崖上  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
点击右上角即可分享
微信分享提示