本文共 1205 字,大约阅读时间需要 4 分钟。
NULL是0
nullptr是空指针void
#includevoid go(int num){ std::cout << "go num" << std::endl;}void go(char *p){ std::cout << "go p" << std::endl;}void main(){ void *p = NULL; go(p);//error C2665: “go”: 2 个重载中没有一个可以转换所有参数类型}
在看例子就比较清晰了:
void go(int num){ std::cout << "go num" << std::endl;}void go(void *p){ std::cout << "go p" << std::endl;}int main(){ void *p = NULL; go(p);//go p go(NULL);//go num go(nullptr);//go p system("pause"); return -1;}
结果:
1)在c语言中NULL代表空指针。
例如:int *i = NULL;
#define NULL ((void*)0) 意思是NULL是void*指针,给int i 赋值的时候隐式转换为相应类型的指针,但是如果换成c++编译器编译的时候会出错,以为c++是强类型的,void 不能隐式转换为其他类型。一般的NULL定义的头文件为:
/* Define NULL pointer value / #ifndef NULL #ifdef __cplusplus #define NULL 0 #else / __cplusplus */
#define NULL ((void )0) #endif / __cplusplus / #endif / NULL */2)c++中 NULL代表0
c++ 中有函数重载的概念,会导致调用二义性。如
void bar(sometype1 a, sometype2 *b);
void bar(sometype1 a, int i);bar(a,NULL)
在C++中,使用0来做为空指针会比使用NULL来做空指针会让你更加警觉。
3)c++11中的nullptr
用nullptr来表示空指针
转载地址:http://iuzjn.baihongyu.com/