设为首页 加入收藏

TOP

C++11 新特性之 nullptr
2015-07-24 06:00:46 来源: 作者: 【 】 浏览:10
Tags:特性 nullptr
对于C和C++程序员来说,一定不会对NULL感到陌生。但是C和C++中的NULL却不等价。NULL表示指针不指向任何对象。

NULL是一个宏定义

在C中将NULL定义为void*指针值为0

#define NULL (void*)0

在C++中,NULL被定义为常数0

#ifndef NULL  
#ifdef __cplusplus  
#define NULL    0  
#else  
#define NULL    ((void *)0)  
#endif  
#endif  

考虑下面的程序

#include 
  
   
#include 
   
     using namespace std; void f(int i) { cout << "f(int)" << endl; } void f(void* ptr) { cout << "f(void*)" << endl; } int main() { f(NULL); return 0; } 
   
  

输出结果:

\


<??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+bnVsbHB0csihtPrBy9PQtO3O88fjz/K1xE5VTEwsbnVsbHB0cr/J0tSxu8DtveLOqta4z/JOVUxMtcTWuNXrPC9wPgo8cD48L3A+CjxwcmUgY2xhc3M9"brush:java;">#include #include using namespace std; void f(int i) { cout << "f(int)" << endl; } void f(void* ptr) { cout << "f(void*)" << endl; } int main() { //f(NULL); f(0); //输出为f(int) f(nullptr); //输出为f(void*) return 0; }
nullptr适用于所有指针类别,包括函数指针和成员指针

const char *pc = str.c_str();
if (pc != nullptr)
	cout << pc << endl;
void (*func)() = nullptr;

不能将nullptr赋值给整形

int i1 = nullptr;    //error
if (i1 == nullptr){} //error
if (nullptr){}       //error
nullptr = 0;         //error







】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇HDU 1106 排序 其实是字符串分割 下一篇猜数字游戏

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: