无法在屏幕上打印nullptr的值

Sta*_*kIT 8 c++ c++11

我正在阅读关于nullptrg ++和VS2010的锻炼和锻炼.

我什么时候做的

#include <iostream>
using namespace std;

auto main(void)->int
{
    int j{};    
    int* q{};   

    cout << "Value of j: " << j << endl; // prints 0
    cout << nullptr << endl;
    cout << "Value of q: " << q << endl; // prints 0

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

打印nullptr屏幕上的值,g ++和VS给出了编译错误.是否不允许打印nullptr屏幕上的值?

For*_*veR 8

指针文字是关键字nullptr.它是std :: nullptr_t类型的prvalue.

类型nullptr_t应该可以转换为T*,但编译器没有operator <<,nullptr_t也不知道要转换的类型nullptr.

你可以用它

cout << static_cast<void*>(nullptr) << endl;
Run Code Online (Sandbox Code Playgroud)


App*_*ish 5

这是因为nullptris 属于 type std::nullptr_t,它没有定义适当的运算符std::cout来打印该类型的对象。您可以像这样自己定义运算符:

//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
}
Run Code Online (Sandbox Code Playgroud)

定义此函数后,它将用于处理所有nullptr通过ostream. 这样你就不需要nullptr每次打印时都进行投射。