NULL和nullptr的区别

NULL是0

nullptr是空指针void

  • 看例子:
#include <iostream>

void 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)

  • 答案是 调用第二个!!!!!!
    调用代码也很快可能忽略过去了,因为我们用的是NULL空指针啊,应该是调用的void bar(sometype1 a, sometype2 *b)这个重载函数啊。实际上NULL在C++中就是0,写NULL这个反而会让你没那么警觉,因为NULL不够“明显”,而这里如果是使用0来表示空指针,那就会够“明显”,因为0是空指针,它更是一个整形常量。

在C++中,使用0来做为空指针会比使用NULL来做空指针会让你更加警觉。

3)c++11中的nullptr

用nullptr来表示空指针

猜你喜欢

转载自blog.csdn.net/qq_22613757/article/details/84146767