iostream vs ostream what is different?

前端 未结 5 1906
孤街浪徒
孤街浪徒 2020-12-31 04:07

As the book says (Exploring C++: The Programmer\'s Introduction to C++):

The istream header declares input operators (>>), and ostream declares outp

相关标签:
5条回答
  • 2020-12-31 04:48

    So After that; I sent email to Bjarne Stroustrup and He replied just like that:
    Personally, I always use iostream and you never need both. ostream exists so that people can #include only the minimaldeclaration needed.

    enter image description here

    0 讨论(0)
  • 2020-12-31 04:49

    I can perfectly run that code without adding #include ostream;

    You happen to be able to on your specific installation. Upgrade your toolchain and that may no longer be the case.

    As of C++11 you can assume it for iostream/ostream, but there are other similar scenarios which C++11 does not cover.

    So, a general rule of thumb: whenever you use a standard library feature, include the header where it's declared/defined, rather than making assumptions and shortcuts.

    0 讨论(0)
  • 2020-12-31 04:52

    As ildjarn noted in the comment, C++ standard from 2003 says that iostream does not necessary include istream and ostream. So, theoretically, the book is correct.

    However, most major compiler vendors have added istream and ostream into iostream, so your code works on the compiler you are using. You might not have such luck on some other compiler.

    If you want to write portable code that would compile on older compilers that only adhere to 2003 standard (or earlier), you should include both headers. OTOH, if you are the only one compiling your code and have control which compilers would be used, it's safe to use iostream only, because that is forward-compatible.

    0 讨论(0)
  • 2020-12-31 04:58

    In C++11, as specified by the standard in §27.4.1, the header iostream includes the istream and ostream headers in itself, so the #include <ostream> is redundant.

    The 'synopsis' of iostream given by the standard in the aforementioned section is

    #include <ios>
    #include <streambuf>
    #include <istream>
    #include <ostream>
    
    namespace std {
        extern istream cin;
        extern ostream cout;
        extern ostream cerr;
        extern ostream clog;
    
        extern wistream wcin;
        extern wostream wcout;
        extern wostream wcerr;
        extern wostream wclog;
    }
    
    0 讨论(0)
  • 2020-12-31 04:58

    You need #include <iostream> to get access to the standard stream objects such as cout. The author of that code is making sure to not rely on the implementation detail that <iostream> includes <ostream> (that wasn't guaranteed prior to C++11).

    You need <ostream> to get access to operator << and std::endl.

    0 讨论(0)
提交回复
热议问题