如何在C ++ 98中定义我们自己的nullptr? [英] How to define our own nullptr in c++98?

查看:152
本文介绍了如何在C ++ 98中定义我们自己的nullptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上,我正在编写所有库类的自己的版本,并且我不想将STL文件包括在类文件中. 因此,例如,我想检查节点是否等于null. 如果我写类似

Actually I am writing my own version of all library classes, and I don't want to include the STL files into my class file. So, for example, I want to check whether the node is equal to null. If I write something like

#define nullptr 0

然后它无法与其他节点指针(即Node *root = nullptr)一起使用

Then it is not working with some other node pointer (i.e. Node *root = nullptr)

推荐答案

书中提到的操作方法:项目25:避免在指针和数字类型上重载" ".

How to do that is mentioned in the book: Effective C++, 2nd edition by Scott Meyers (newer edition is available) in chapter: "Item 25: Avoid overloading on a pointer and a numerical type.".

如果您的编译器不知道 nullptr 由C ++ 11引入的关键字.

It is needed if your compiler doesn't know the nullptr keyword introduced by C++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     */

那本书绝对值得一读.

nullptr 的优势://en.cppreference.com/w/cpp/types/NULL"rel =" nofollow noreferrer> NULL 是,nullptr的作用类似于真实的指针类型,因此它增加了类型安全性,而NULL就像一个整数,在C ++ 11之前的版本中设置为0.

The advantage of nullptr over NULL is, that nullptr acts like a real pointer type thus it adds type safety whereas NULL acts like an integer just set to 0 in pre C++11.

这篇关于如何在C ++ 98中定义我们自己的nullptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆