简体   繁体   English

为什么这段代码会编译? cout <“tt”;

[英]Why does this code compile? cout < “tt”;

cout is object of class ostream , and ostream is typedef of basic_ostream : cout是类ostream对象, ostreambasic_ostream typedef:

extern ostream cout;

typedef basic_ostream<char> ostream;

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

but none of these classes has operator< 但这些类都没有operator<

So I can't understand why this code compiles without any errors: 所以我无法理解为什么这段代码编译没有任何错误:

std::cout < "aaa";

In C++ language operator < makes the compiler to consider a built-in candidate function of the form 在C ++语言中,运算符<使编译器考虑表单的内置候选函数

bool operator<(T, T);

for every possible pointer type T . 对于每个可能的指针类型T In particular, that means that there's such a function for void * type. 特别是,这意味着void *类型具有这样的功能。 This is the function that is applicable in your case. 这是适用于您的情况的功能。 String literal is implicitly convertible to void * and std::cout is also implicitly convertible to void * . 字符串文字可以隐式转换为void *std::cout也可以隐式转换为void *

You can reproduce the same behavior with the following minimalist example 您可以使用以下极简主义示例重现相同的行为

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

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

The above would apply to C++03. 以上内容适用于C ++ 03。 I'm not sure why it compiles in C+11 tough (assuming it does), since in C++11 stream conversion to void * was replaced with explicit conversion to bool . 我不确定为什么它在C + 11中编译很难(假设它确实如此),因为在C ++ 11中,流转换为void *显式转换为bool所取代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM