初始化指针

来源:互联网 发布:现在最流行的网络词语 编辑:程序博客网 时间:2024/05/26 05:52
#include<iostream>using namespace std;int main(){int *a(nullptr), *b(NULL), *c(0);if(!a) cout<<" 'a' does not point to anything. \n";if(!b) cout<<" 'b' does not point to anything. \n";if(!c) cout<<" 'c' does not point to anything. \n";return 0;}

nullptr C++新标准引入的特性, Visual C++ 2010 编译器支持它。过去已经使用0NULL(编译器将用0代替此宏)来初始化指针,当然它们现在仍然可以使用。但是,使用nullptr初始化指针要好得多。

因为字面值nullptr可以隐式转换为bool类型,所以我们可以如下面这样来检查指针的状态:

if(!a) 

cout<<" 'a' does not point to anything. \n"; 

nullptr转换为boolfalse,其他任何指针值都可以为true


1 0
原创粉丝点击