为什么std :: nullptr_t在C ++中不能与std :: cout一起使用? [英] Why does not std::nullptr_t work with std::cout in C++?
问题描述
我了解了std::nullptr_t
,它是空指针文字nullptr
的类型.
I learned about std::nullptr_t
that is the type of the null pointer literal, nullptr
.
然后我制作了一个小程序:
Then I made small program :
#include <iostream>
int main()
{
std::nullptr_t n1;
std::cout<<n1<<endl;
return 0;
}
在这里,nullptr_t
是数据类型,而n1
是变量,我正在尝试打印变量的值.但是,编译器给出了一个错误:
Here, nullptr_t
is data type and n1
is variable and I'm trying to print the value of variable. But, Compiler give an error:
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
一起使用?我这是怎么了?
Why does not std::nullptr_t
work with std::cout
in C++? What am I wrong here?
推荐答案
operator<<
输出流具有多种不同类型的指针的重载,但不是std::nullptr_t
1 .这意味着编译器无法确定要调用的重载,因为 any 接受指针的重载同样好. (例如,它接受C样式的字符串的char const *
以及接受输出原始指针值的void const *
.)
operator<<
for output streams has overloads for multiple different types of pointers, but not std::nullptr_t
1. This means that the compiler cannot determine which overload to call, because any of the overloads accepting a pointer are equally good. (For example, it accepts char const *
for C-style strings, and also void const *
, which will output the raw pointer value.)
解决此问题的一种方法是定义自己的重载,强制使用void const *
重载:
One option to fix this would be to define your own overload that forces the use of the void const *
overload:
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";
}
注意:
Notes:
-
正如注释中指出的,
- 1 ,C ++ 17中有一个接受
std::nullptr_t
的重载,因此如果您使用的是合格的C ++ 17,这将不再是一个问题.实施. -
endl
需要std::
资格-但无论如何都应该在这里使用'\n'
. (std::endl
仅是需要冲洗流的好主意.)
- 1 As pointed out in the comments, there is an overload accepting
std::nullptr_t
in C++17, so this will cease to be an issue if you are using a conforming C++17 implementation. endl
needsstd::
-qualification -- but you should use'\n'
here anyway. (std::endl
is only a good idea when you need the stream flushed.)
这篇关于为什么std :: nullptr_t在C ++中不能与std :: cout一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!