C++之NULL and nullptr
C++11标准之前:
1. int * ptr = NULL;
然而存在一个小问题,上代码:
#include <iostream>
#include <string>
using namespace std;
void func(int* num)
{
cout << "this is the ptr function..." << endl;
}
void func(int num)
{
cout << "this is the normal function..." << endl;
}
void main(int argc, char** argv)
{
func(NULL);
}
输出的结果并不是想象之中的this is the ptr function…,而是this is the normal function…
实践出真知,上图:
原因:
C++11标准之前,编译器进行解释程序时,NULL会被直接解释成0(int),所以这里的参数不是表面的NULL而是0,0是整数啊.
C++11的出现后为了规避这个问题,nullptr在C++11中就是代表空指针,补充一下:
0和NULL
C语言中将null作为(void *)类型,而C++将null作为int类型,整数值0.nullptr和void *
nullptr习惯被称作指针空
void*习惯被称作无类型指针nullptr和nullptr_t
nullptr习惯被称作指针空
nullptr_t习惯被称作指针空值类型
即表示指针空值类型并非仅有nullptr一个实例
可以通过nullptr_t来声明一个指针空值类型的变量
通过之上的理解,可以解释nullptr是一个字面值常量,类型为std::nullptr_t,空指针常数可以转换为任意类型的指针类型。
在c++中(void )不能转化为任意类型的指针,即 int *p=(void)是错误的,但int *p=nullptr是正确的,原因
对于函数重载:若c++中 (void *)支持任意类型转换,函数重载时将出现问题下列代码中fun(NULL)将不能判断调用哪个函数
void fun(int i){cout<<"1";};
void fun(char *p){cout<<"2";};
int main()
{
fun(NULL); //输出1,c++中NULL为整数0
fun(nullptr);//输出2,nullptr 为空指针常量。是指针类型
}