【问题标题】:Why does this code compile? cout < "tt";为什么这段代码会编译? cout < "tt";
【发布时间】:2014-02-19 21:50:10
【问题描述】:

coutostream 类的对象,ostreambasic_ostream 的 typedef:

extern ostream cout;

typedef basic_ostream<char> ostream;

template <class charT, class traits = char_traits<charT> >
  class basic_ostream;

但是这些类都没有operator&lt;

所以我不明白为什么这段代码编译时没有任何错误:

std::cout < "aaa";

【问题讨论】:

  • en.cppreference.com/w/cpp/io/basic_ios/operator_bool - 从它的编译来看,它使用的是void *,所以它触发了未定义的行为,因为指针不相关。
  • @omid 只是为了让您理解上面的评论,您使用的是“
  • @chris 我正在使用 c++11 。为什么它使用 void* ?
  • @omid,AFAIK,较新版本的 libc++ 进行了切换,但还没有其他任何东西。我可能是错的,但可以肯定的是你的图书馆没有。
  • 顺便说一句,std::ostream 不是std::basic_ostream 的对象,它是typedefstd::basic_ostream&lt;char&gt;,一个窄字符输出流。

标签: c++ stl cout ostream


【解决方案1】:

在 C++ 语言中,运算符 &lt; 使编译器考虑一个内置候选函数的形式

bool operator<(T, T);

对于每个可能的指针类型T。特别是,这意味着void * 类型有这样一个函数。这是适用于您的情况的功能。字符串字面量可隐式转换为void *std::cout 也可隐式转换为void *

您可以使用以下极简示例重现相同的行为

struct X {
  operator void *() { return 0; }
};

int main() {
  X() < "";
}

以上内容适用于 C++03。我不确定为什么它在 C+11 中很难编译(假设确实如此),因为在 C++11 中,流转换为 void *explicit 转换为 bool 所取代。

【讨论】:

  • 我 99% 确定这只是标准库实现的追赶。
猜你喜欢
  • 2021-12-17
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 2013-08-08
相关资源
最近更新 更多