Some tips about <iostream>
One advantage of <iostream> over <stdio.h> (which includes C-style scanf and printf) is that built-in types like int are read and written in the same manner as user-defined types like Rational:
|
|
So considering type safety and extensibility offered by the classes and functionas in the iosteam library, in general we should prefer <iostream> to <stdio.h>. In order for this code to compile, we mus define operator>> and operator<< for Rational type. A typical output routine may look like this:
|
|
There are some subtle points worth noting: operator<< is not a member function (explained in item 19) and the Rational object to be output is passed as a reference-to-const rather than as an object (see item 22).
Howerver, there are still very few situations where <stdio.h> may be more sensible to use:
- Some implementations of iostream operations are less efficient than corresponding C stream operations, so it may make sense for applications requiring extreme performance.
- During the course of standardization, iostream library was modified in some fundamental ways, so it may make sense for applications targeting at maximum portablility.
- Since classes of the iostream library have constructors while functions in
<stdio.h>do not, when concerning about initialization order of static objects (see item 47) the standard C library may be more useful because you can always call it with impunity.
By the way
Technically speaking, the standardizatoin committee eliminated <iostream.h> in favor of <iostream> when they truncated the names of the other non-C standard header names, but chances are that most compilers support both of them. However, there is a subtle difference between them:
- when
#include <iostream>, the iostream library is ensconced within the namespacestd(item 28) - when
#include <iostream.h>, we get the same elements but they are at global scope
Thus we usually prefer using <iostream> for name conflicts consideration.