实际上我正在编写我自己的所有库类的版本,我不想将STL文件包含到我的类文件中.因此,例如,我想检查节点是否等于null.如果我写的东西像
#define nullptr 0
Run Code Online (Sandbox Code Playgroud)
然后它不使用其他节点指针(即Node *root = nullptr)
如何做到这一点在书中提到:有效的C++,Scott Meyers的第2版(更新的版本可用)在章节:" 第25项:避免指针上的重载和数字类型. ".
如果您的编译器不知道nullptrC++ 11引入的关键字,则需要它.
const /* this is a const object... */
class nullptr_t
{
public:
template<class T> /* convertible to any type */
operator T*() const /* of null non-member */
{ return 0; } /* pointer... */
template<class C, class T> /* or any type of null */
operator T C::*() const /* member pointer... */
{ return 0; }
private:
void operator&() const; /* Can't take address of nullptr */
} nullptr = {}; /* and whose name is nullptr */
Run Code Online (Sandbox Code Playgroud)
这本书绝对值得一读.
nullptrover 的优点NULL是,它nullptr像一个真正的指针类型,因此它增加了类型安全性,而NULL在预C++ 11中就像一个整数设置为0.
您不应该定义具有关键字标识符的宏.
即使您不使用STL,也不需要定义自己的nullptr,因为它不是STL(也不是标准库)的一部分,而是(C++)语言本身的一部分.
| 归档时间: |
|
| 查看次数: |
1503 次 |
| 最近记录: |