📄 ei2.htm
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML LANG="EN">
<HEAD>
<title>Effective C++, 2E | Item 2: Prefer <iostream> to <stdio.h></TITLE>
<LINK REL=STYLESHEET HREF=../INTRO/ECMEC.CSS>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/COOKIE.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">var imagemax = 0; setCurrentMax(0);</SCRIPT>
<SCRIPT LANGUAGE="Javascript" SRC="../JAVA/DINGBATS.JS"></SCRIPT>
<SCRIPT LANGUAGE="Javascript">
var dingbase = "EI2_DIR.HTM";
var dingtext = "Item E2, P";
if (self == top) {
top.location.replace(dingbase + this.location.hash);
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000" ONLOAD="setResize()">
<!-- SectionName="E2: Prefer <iostream> to <stdio.h>" -->
<A NAME="95970"></A>
<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./EI1_FR.HTM" TARGET="_top">Item 1: Prefer const and inline to #define.</A> <BR> Continue to <A HREF="./EI3_FR.HTM" TARGET="_top">Item 3: Prefer new and delete to malloc and free.</A></FONT></DIV>
<P><A NAME="dingp1"></A><FONT ID="eititle">Item 2: Prefer <CODE><iostream></CODE> to <CODE><stdio.h></CODE>.</FONT><SCRIPT>create_link(1);</SCRIPT>
</P>
<A NAME="95971"></A>
<P><A NAME="dingp2"></A>
Yes, they're portable. Yes, they're efficient. Yes, you already know how to use them. Yes, yes, yes. But venerated though they are, the fact of the matter is that <CODE>scanf</CODE> and <CODE>printf</CODE> and all their ilk could use some improvement. In particular, they're not type-safe and they're not extensible. Because type safety and extensibility are cornerstones of the C++ way of life, you might just as well resign yourself to them right now. Besides, the <CODE>printf</CODE>/<CODE>scanf</CODE> family of functions separate the variables to be read or written from the formatting information that controls the reads and writes, just like FORTRAN does. It's time to bid the 1950s a fond <NOBR>farewell.<SCRIPT>create_link(2);</SCRIPT>
</NOBR></P>
<A NAME="1819"></A>
<P><A NAME="dingp3"></A>
Not surprisingly, these weaknesses of <CODE>printf</CODE>/<CODE>scanf</CODE> are the strengths of <CODE>operator>></CODE> and <CODE>operator<<</CODE>.<SCRIPT>create_link(3);</SCRIPT>
</P>
<A NAME="1820"></A>
<UL><PRE>int i;
Rational r; // r is a rational number
</PRE>
</UL><A NAME="12678"></A>
<UL><PRE>...
</PRE>
</UL><A NAME="1821"></A>
<UL><PRE>cin >> i >> r;
cout << i << r;
</PRE>
</UL><A NAME="1822"></A>
<P><A NAME="dingp4"></A>
If this code is to compile, there must be functions <CODE>operator>></CODE> and <CODE>operator<<</CODE> that can work with an object of type <CODE>Rational</CODE> (possibly via implicit type conversion — see <A HREF="../MEC/MI5_FR.HTM#5970" TARGET="_top">Item M5</A>). If these functions are missing, it's an error. (The versions for <CODE>int</CODE>s are standard.) Furthermore, compilers take care of figuring out which versions of the operators to call for different variables, so you needn't worry about specifying that the first object to be read or written is an <CODE>int</CODE> and the second is a <CODE>Rational</CODE>.<SCRIPT>create_link(4);</SCRIPT>
</P>
<A NAME="213141"></A>
<P><A NAME="dingp5"></A>
In addition, objects to be read are passed using the same syntactic form as are those to be written, so you don't have to remember silly rules like you do for <CODE>scanf</CODE>, where if you don't already have a pointer, you have to be sure to take an address, but if you've already got a pointer, you have to be sure <I>not</I> to take an address. Let C++ compilers take care of those details. They have nothing better to do, and you <I>do</I> have better things to do. Finally, note that built-in types like <CODE>int</CODE> are read and written in the same manner as user-defined types like <CODE>Rational</CODE>. Try <I>that</I> using <CODE>scanf</CODE> and <CODE>printf</CODE>!<SCRIPT>create_link(5);</SCRIPT>
</P>
<A NAME="1824"></A>
<P><A NAME="dingp6"></A>
Here's how you might write an output routine for a class representing rational <NOBR>numbers:<SCRIPT>create_link(6);</SCRIPT>
</NOBR></P>
<A NAME="1825"></A><A NAME="p18"></A>
<UL><PRE>class Rational {
public:
Rational(int numerator = 0, int denominator = 1);
</PRE>
</UL><A NAME="1826"></A>
<UL><PRE> ...
</PRE>
</UL><A NAME="16827"></A>
<UL><PRE>private:
int n, d; // numerator and denominator
</PRE>
</UL><A NAME="1827"></A>
<UL><PRE>friend ostream& operator<<(ostream& s, const Rational& r);
};
</PRE>
</UL><A NAME="12701"></A>
<UL><PRE>ostream& operator<<(ostream& s, const Rational& r)
{
s << r.n << '/' << r.d;
return s;
}
</PRE>
</UL><A NAME="1830"></A>
<P><A NAME="dingp7"></A>
This version of <CODE>operator<<</CODE> demonstrates some subtle (but important) points that are discussed elsewhere in this book. For example, <CODE>operator<<</CODE> is not a member function (<A HREF="./EI19_FR.HTM#5887" target="_top">Item 19</A> explains why), and the <CODE>Rational</CODE> object to be output is passed into <CODE>operator<<</CODE> as a reference-to-<CODE>const</CODE> rather than as an object (see <A HREF="./EI22_FR.HTM#6133" TARGET="_top">Item 22</A>). The corresponding input function, <CODE>operator>></CODE>, would be declared and implemented in a similar <NOBR>manner.<SCRIPT>create_link(7);</SCRIPT>
</NOBR></P>
<A NAME="1832"></A>
<P><A NAME="dingp8"></A>
Reluctant though I am to admit it, there are some situations in which it may make sense to fall back on the tried and true. First, some implementations of iostream operations are less efficient than the corresponding C stream operations, so it's possible (though unlikely — see <A HREF="../MEC/MI16_FR.HTM#40995" TARGET="_top">Item M16</A>) that you have an application in which this makes a significant difference. Bear in mind, though, that this says nothing about iostreams <I>in general</I>, only about particular implementations; see <A HREF="../MEC/MI23_FR.HTM#41253" TARGET="_top">Item M23</A>. Second, the iostream library was modified in some rather fundamental ways during the course of its standardization (see <A HREF="./EI49_FR.HTM#8392" TARGET="_top">Item 49</A>), so applications that must be maximally portable may discover that different vendors support different approximations to the standard. Finally, because the classes of the iostream library have constructors and the functions in <CODE><stdio.h></CODE> do not, there are rare occasions involving the initialization order of static objects (see <A HREF="./EI47_FR.HTM#8299" TARGET="_top">Item 47</A>) when the standard C library may be more useful simply because you know that you can always call it with <NOBR>impunity.<SCRIPT>create_link(8);</SCRIPT>
</NOBR></P>
<A NAME="3794"></A>
<P><A NAME="dingp9"></A>
The type safety and extensibility offered by the classes and functions in the iostream library are more useful than you might initially imagine, so don't throw them away just because you're used to <CODE><stdio.h></CODE>. After all, even after the transition, you'll still have your <NOBR>memories.<SCRIPT>create_link(9);</SCRIPT>
</NOBR></P>
<A NAME="223413"></A>
<P><A NAME="dingp10"></A>
<A NAME="p19"></A>Incidentally, that's no typo in the Item title; I really
mean <CODE><iostream></CODE> and not <CODE><iostream.h></CODE>.
Technically speaking, there is no such thing as
<CODE><iostream.h></CODE> — the <NOBR><FONT COLOR="#FF0000"
SIZE="-2"><B>°</B></FONT><A
HREF="http://www.awl.com/cseng/cgi-bin/cdquery.pl?name=committee" onMouseOver
= "self.status = 'Link to the C++ Standardization Committee'; return true"
onMouseOut = "self.status = self.defaultStatus"
TARGET="_top">standardization</NOBR> committee</A> eliminated it in favor of
<CODE><iostream></CODE> when they truncated the names of the other
non-C standard header names. The reasons for their doing this are explained
in <A HREF="./EI49_FR.HTM#8392" TARGET="_top">Item 49</A>, but what you
really need to understand is that if (as is likely) your compilers support
both <CODE><iostream></CODE> and <CODE><iostream.h></CODE>, the
headers are subtly different. In particular, if you <CODE>#include</CODE>
<CODE><iostream></CODE>, you get the elements of the iostream library
ensconced within the namespace <CODE>std</CODE> (see <A
HREF="./EI28_FR.HTM#6429" TARGET="_top">Item 28</A>), but if you
<CODE>#include</CODE> <CODE><iostream.h></CODE>, you get those same
elements at global scope. Getting them at global scope can lead to name
conflicts, precisely the kinds of name conflicts the use of namespaces is
designed to prevent. Besides, <CODE><iostream></CODE> is less to type
than <CODE><iostream.h></CODE>. For many people, that's reason enough
to prefer <NOBR>it.<SCRIPT>create_link(10);</SCRIPT>
</NOBR></P> <DIV
ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="./EI1_FR.HTM"
TARGET="_top">Item 1: Prefer const and inline to #define.</A>
<BR> Continue to <A HREF="./EI3_FR.HTM"
TARGET="_top">Item 3: Prefer new and delete to malloc and
free.</A></FONT></DIV>
</BODY>
</HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -