无法在屏幕上打印 nullptr 的值
Unable to print the value of nullptr on screen
我正在阅读有关nullptr
的信息,并在g++和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;
}
在屏幕上打印nullptr
的值,g++ 和 VS 给出了编译器错误。不允许在屏幕上打印nullptr
的值吗?
指针文字是关键字 nullptr。它是 std::nullptr_t 类型的 prvalue。
类型 nullptr_t 应该可以转换为 T*
,但编译器没有nullptr_t
operator <<
,并且不知道要nullptr
转换为哪种类型。
你可以使用这个
cout << static_cast<void*>(nullptr) << endl;
这是因为nullptr
的类型是 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
}
定义此函数后,它将用于处理通过ostream
打印nullptr
的所有尝试。这样,您就不需要每次打印时都投射nullptr
。
我在
编写一些类型参数化的测试代码(使用模板)时遇到了这个问题。我需要打印一个类型 T
的值,其中 nullptr_t
是 T
的有效类型。我想出了一个解决方案,其中要打印的值被包装在一个printable
模板函数中。然后,此函数利用模板专用化来提供使用nullptr_t
时所需的行为。
#include <cstddef>
#include <iostream>
template <typename T> struct Printable
{
Printable(const T& val) : val(val) {}
void print(std::ostream& out) const {out << val;}
const T& val;
};
template <> struct Printable<std::nullptr_t>
{
Printable(nullptr_t) {}
void print(std::ostream& out) const {out << "null";}
};
template <typename T>
Printable<T> printable(const T& value) {return Printable<T>(value);}
template <typename T>
std::ostream& operator<<(std::ostream& out, const Printable<T>& p)
{
p.print(out);
return out;
}
int main() {
std::cout << printable(42) << " " << printable(nullptr) << "n";
return 0;
}
Ideone link
相关文章:
- 如何循环打印顶点结构
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 如何在c++中打印目录
- 如何在自删除后将对象设置为nullptr
- 如何取消对nullptr的屏蔽,返回正确的对象
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 在线编译器中的分段C++没有打印消息
- C++ - "!pointer"和"pointer == nullptr"的区别?
- 在C++中打印指向不同基元数据类型的指针的内存地址
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何将结构插入到集合中并打印集合的成员
- 在循环C++中指定字符串之后,不会打印该字符串
- 以螺旋方式打印矩阵的程序.(工作不好)
- 从控制台中删除最后打印的元素
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 如何仅使用对象名称打印特定于对象的成员
- 回溯C++不打印函数,因此文件
- 无法在屏幕上打印 nullptr 的值
- 为什么 std::cout 只有在函数返回时才可以打印 nullptr 的值