C++11 新特性之 nullptr
时间:2014-06-15 10:22:49
收藏:0
阅读:359
对于C和C++程序员来说,一定不会对NULL感到陌生。但是C和C++中的NULL却不等价。NULL表示指针不指向任何对象。
NULL是一个宏定义
在C++中,NULL被定义为常数0
考虑下面的程序
nullptr适用于所有指针类别,包括函数指针和成员指针
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 <iostream>
#include <typeinfo>
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;
}
输出结果:
nullptr取代了有错误倾向的NULL,nullptr可以被理解为指向NULL的指针
#include <iostream>
#include <typeinfo>
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
评论(0)