为什么 std::nullptr_t 不能与 std::cout 一起使用C++?

Why does not std::nullptr_t work with std::cout in C++?

本文关键字:std 一起 cout C++ 不能 nullptr 为什么      更新时间:2023-10-16

我了解了std::nullptr_t这是空指针文字的类型,nullptr.

然后我做了小程序:

#include <iostream>
int main() 
{
std::nullptr_t n1; 
std::cout<<n1<<endl;
return 0;
} 

在这里,nullptr_t是数据类型,n1是变量,我正在尝试打印变量的值。但是,编译器给出一个错误:

prog.cpp: In function 'int main()':
prog.cpp:6:11: error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::nullptr_t')
std::cout<<n1<<endl;

为什么std::nullptr_t不与C++中的std::cout一起使用?我在这里错了什么?

输出流的operator<<对多种不同类型的指针具有重载,但不是std::nullptr_t1。这意味着编译器无法确定要调用哪个重载,因为接受指针的任何重载都同样好。(例如,它接受 C 样式字符串的char const *,也接受void const *,这将输出原始指针值。

解决此问题的一种选择是定义自己的重载,强制使用void const *重载:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
return s << static_cast<void *>(nullptr);
}

或者让它做其他事情:

std::ostream & operator<<(std::ostream &s, std::nullptr_t) {
return s << "nullptr";
}

笔记:

  • 1正如评论中指出的,C++17 中存在接受std::nullptr_t的重载,因此如果您使用的是符合标准的 C++17 实现,这将不再是问题。
  • endl需要std::限定 - 但无论如何你应该在这里使用'n'。 (仅当您需要刷新流时,std::endl才是一个好主意。