C语言nullptr错误,C++之‘nullptr’ was not declared in this scope

在vim里面写了一个简单cpp文件,为了避免野指针,需要指针初始化

char *p2 = nullptr

1、编译时报错如下

0818b9ca8b590ca3270a3433284dd417.png

2、解决办法

编译加上

g++ -std=gnu++0x int.cpp -o int

3、C里面的null和C++里面的nullptr、NULL介绍

NULL在C++中的定义

/* Define NULL pointer value */

#ifndef NULL

#ifdef __cplusplus

#define NULL 0

#else /* __cplusplus */

#define NULL ((void *)0)

#endif /* __cplusplus */

#endif /* NULL */C++中 NULL在C++中被明确定义为整数0

NULL在C中的定义

#define NULL ((void *)0)

C中NULL实质上是一个void *指针

比如下面代码

void F(char *);

void F(int);

int main()

{

F(NULL);

}C++让NULL也支持void *的隐式类型转换,这样编译器就不知道应该调用哪一个函数

F(NULL)应该调用的是F(char *)但实际上NULL的值是0,所以调用了Func(int)。nullptr关键字真是为了解决这个问题而引入的。

另外我们还有注意到NULL只是一个宏定义,而nullptr是一个C++关键字

4、nullptr一般使用:

nullptr关键字用于标识空指针,是std::nullptr_t类型的(constexpr)变量。它可以转换成任何指针类型和bool布尔类型,但是不能被转换为整数。

char *p1 = nullptr; // 正确

int *p2 = nullptr; // 正确

bool b = nullptr; // 正确. if(b)判断为false

int a = nullptr; // error