首页 > 其他分享 >NULL与nullptr

NULL与nullptr

时间:2022-12-08 21:15:14浏览次数:29  
标签:main int void nullptr C++ Print NULL

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,作为指针的初始化。

标签:main,int,void,nullptr,C++,Print,NULL
From: https://www.cnblogs.com/zhzm/p/16967283.html

相关文章