""空字符串,會建立一個對象,分配內存空間ios
NULL,不會建立對象,不會分配內存空間,意思是不存在的ide
#include <iostream> using namespace std; int main() { std::string strTemp; if( strTemp.empty() ) { cout<<"is empty "<<endl; } else { cout<<"is not empty"<<endl; } strTemp = ""; if( strTemp.empty() ) { cout<<"is empty"<<endl; } else { cout<<"is not empty"<<endl; } if( strTemp == "" ) { cout<<"is empty"<<endl; } else { cout<<"is not empty"<<endl; } /* if( strTemp == NULL ) { cout<<"is empty"<<endl; } else { cout<<"is not empty"<<endl; } */ return 0; }
在如下代碼最後,用NULL與字符類型進行比較,會直接致使編譯錯誤!spa
test.cpp:37:17: error: no match for ‘operator==’ in ‘strTemp == 0’orm
從編譯的錯誤提示看:NULL爲數值0對象
#include <iostream> using namespace std; int main() { if( NULL == 0 ) { cout<<"NULL is number 0"<<endl; } else { cout<<"NULL is not number 0"<<endl; } int nNum; cout<<"nNUm = "<<nNum<<endl; nNum = NULL; cout<<"nNUm = "<<nNum<<endl; cout<<static_cast<void*>(NULL)<<endl; return 0; }
從這段代碼,進一步驗證了,NULL對就的值爲數值0,地址爲空內存
注意:將NULL賦值爲int變量時會報警告字符串
NULL.cpp:18:9: warning: converting to non-pointer type ‘int’ from NULL [-Wconversion-null]string