简体   繁体   中英

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

cout is object of class ostream , and ostream is typedef of basic_ostream :

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<

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

bool operator<(T, T);

for every possible pointer type T . In particular, that means that there's such a function for void * type. 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 * .

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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