网站首页 > 精选文章 / 正文
C++中NULL和nullptr的区别:
NULL来自c语言,一般由宏定义实现,而nullptr是C++11新增加的关键字。
在c语言当中 NULL定义为
#define NULL ((void *)0)
在C++语言当中 NULL定义为整数0。
#define NULL 0
一般编译器定义如下:
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
C++中,NULL为0会带来一个问题,无法与整数0进行区分,尤其在函数重载的时候会有大问题:
#include <iostream>
// 函数重载:一个接受char*,另一个接受int
void processInput(char* input) {
if (input == nullptr) {
std::cout << "No string provided.\n";
}
else {
std::cout << "Processing string: " << input << "\n";
}
}
void processInput(int number) {
if (number == 0) {
std::cout << "Number is zero.\n";
}
else {
std::cout << "Processing number: " << number << "\n";
}
}
int main() {
// 调用重载函数
processInput(NULL);
return 0;
}
上面的代码在传入NULL时,会把NULL当中整数0来看待。所以C++11中引入了nullptr来解决这个问题
nullptr是一个类型安全的空指针字面量,专门用于初始化或赋值给指针类型,而不会被隐式转换为整型或其他非指针类型。这使得nullptr能够明确地区分整型和指针类型,避免了以前使用NULL或0作为空指针时可能产生的类型混淆和潜在的运行时错误。
#include <iostream>
void func(int num) {
std::cout << "Called func with int: " << num << std::endl;
}
int main() {
int* ptr = nullptr; // 正确:nullptr可以赋值给指针
// 下面的代码在C++11及更高版本中会产生编译错误
// func(nullptr); // 错误:nullptr不能转换为int类型
return 0;
}
在上面这个例子中,nullptr可以安全地赋值给int*类型的指针ptr,但不能作为参数传递给期望整型的func函数。尝试这样做会导致编译错误,因为nullptr不能被转换为整型。
Tags:ifnull用法
- 上一篇:嵌入式开发必学 ,状态机常用的几种骚操作
- 下一篇:MySQL--常用函数
猜你喜欢
- 2025-05-30 程序猿才懂得幽默……第N波
- 2025-05-30 OC中nil、Nil、NULL与NSNull的一些理解
- 2025-05-30 知道空指针,你也能改bug了
- 2025-05-30 JavaScript中关于null的一切
- 2025-05-30 Excel中IFERROR函数的使用方法
- 2025-05-30 3分钟短文 | PHP判断null,别再 == 了,你真控制不住
- 2025-05-30 「Java」一张图教会你关于null的几种处理方式(内附代码)
- 2025-05-30 没用 Java 8,怎么优雅地避免空指针?
- 2025-05-30 MySQL--常用函数
- 2025-05-30 嵌入式开发必学 ,状态机常用的几种骚操作