Unable to print the value of nullptr on screen

后端 未结 3 962
北荒
北荒 2020-12-06 18:33

I was reading about nullptr and doing workout on g++ and also on VS2010.

When I did

#include 
using namespace std;

aut         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 18:53

    This is because nullptr is of type std::nullptr_t, which does not define the appropriate operators for std::cout to be able print objects of that type. You can define the operator yourself like this:

    //std::cout is of type std::ostream, and nullptr is of type std::nullptr_t
    std::ostream& operator << (std::ostream& os, std::nullptr_t ptr)
    {
        return os << "nullptr"; //whatever you want nullptr to show up as in the console
    }
    

    After this function is defined, it will be used to handle all attempts to print nullptr via an ostream. This way you don't need to cast nullptr every time you print it.

提交回复
热议问题