⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ec4.htm

📁 一个非常适合初学者入门的有关c++的文档
💻 HTM
📖 第 1 页 / 共 5 页
字号:
</NOBR></P>
<A NAME="76970"></A>
<UL><PRE>result = oneHalf * 2;             // error!
result = 2 * oneHalf;             // error!
</PRE>
</UL><A NAME="76968"></A>
<P><A NAME="dingp61"></A>
That would hardly qualify as support for mixed-mode arithmetic, but at least the behavior of the two statements would be <NOBR>consistent.<SCRIPT>create_link(61);</SCRIPT>
</NOBR></P>
<A NAME="76976"></A>
<P><A NAME="dingp62"></A>
The <CODE>Rational</CODE> class we've been examining, however, is designed to allow implicit conversions from built-in types to <CODE>Rational</CODE>s &#151; that's why <CODE>Rational</CODE>'s constructor isn't declared <CODE>explicit</CODE>. That being the case, compilers will perform the implicit conversion necessary to allow <CODE>result</CODE>'s first assignment to compile. In fact, your handy-dandy compilers will perform this kind of implicit type conversion, if it's needed, on <I>every</I> parameter of <I>every</I> function call. But they will do it only for parameters <I>listed in the parameter list</I>, <I>never </I>for the object on which a member function is invoked, i.e., the object corresponding to <CODE>*this</CODE> inside a member function. That's why this call <NOBR>works,<SCRIPT>create_link(62);</SCRIPT>
</NOBR></P>
<A NAME="5935"></A>
<UL><PRE>result = oneHalf.operator*(2);      // converts int -&gt; Rational
</PRE>
</UL><A NAME="5936"></A>
<A NAME="dingp63"></A>and this one does not:<SCRIPT>create_link(63);</SCRIPT>

<A NAME="5937"></A>
<UL><PRE>result = 2.operator*(oneHalf);      // doesn't convert
                                    // int -&gt; Rational
</PRE>
</UL><A NAME="5938"></A>
<P><A NAME="dingp64"></A>
The first case involves a parameter listed in the function declaration, but the second one does <NOBR>not.<SCRIPT>create_link(64);</SCRIPT>
</NOBR></P>
<A NAME="5939"></A>
<P><A NAME="dingp65"></A>
Nonetheless, you'd still like to support mixed-mode arithmetic, and the way to do it is by now perhaps clear: make <CODE>operator*</CODE> a non-member function, thus allowing compilers to perform implicit type conversions on <I>all</I> <NOBR>arguments:<SCRIPT>create_link(65);</SCRIPT>
</NOBR></P>
<A NAME="5940"></A>
<UL><PRE>class Rational {
</PRE>
</UL><A NAME="5941"></A>
<UL><PRE>  ...                               // contains no operator*
</PRE>
</UL><A NAME="5942"></A>
<UL><PRE>};
</PRE>
</UL><A NAME="5944"></A>
<UL><PRE><A NAME="p87"></A>// declare this globally or within a namespace; see
// <A HREF="../MEC/MC4_FR.HTM#45310" TARGET="_top">Item M20</A> for why it's written as it is
const Rational operator*(const Rational&amp; lhs,
                         const Rational&amp; rhs)
{
  return Rational(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
}
</PRE>
</UL><A NAME="5945"></A>
<UL><PRE>Rational oneFourth(1, 4);
Rational result;
</PRE>
</UL><A NAME="5946"></A>
<UL><PRE>result = oneFourth * 2;           // fine
result = 2 * oneFourth;           // hooray, it works!
</PRE>
</UL><A NAME="5948"></A>
<P><A NAME="dingp66"></A>
This is certainly a happy ending to the tale, but there is a nagging worry. Should <CODE>operator*</CODE> be made a friend of the <CODE>Rational</CODE> <NOBR>class?<SCRIPT>create_link(66);</SCRIPT>
</NOBR></P>
<A NAME="5949"></A>
<P><A NAME="dingp67"></A>
In this case, the answer is no, because <CODE>operator*</CODE> can be implemented entirely in terms of the class's public interface. The code above shows one way to do it. Whenever you can avoid friend functions, you should, because, much as in real life, friends are often more trouble than they're <NOBR>worth.<SCRIPT>create_link(67);</SCRIPT>
</NOBR></P>
<A NAME="17846"></A>
<P><A NAME="dingp68"></A>
However, it's not uncommon for functions that are not members, yet are still conceptually part of a class interface, to need access to the non-public members of the <NOBR>class.<SCRIPT>create_link(68);</SCRIPT>
</NOBR></P>
<A NAME="5950"></A>
<P><A NAME="dingp69"></A>
As an example, let's fall back on a workhorse of this book, the <CODE>String</CODE> class. If you try to overload <CODE>operator&gt;&gt;</CODE> and <CODE>operator&lt;&lt;</CODE> for reading and writing <CODE>String</CODE> objects, you'll quickly discover that they shouldn't be member functions. If they were, you'd have to put the <CODE>String</CODE> object on the left when you called the <NOBR>functions:<SCRIPT>create_link(69);</SCRIPT>
</NOBR></P>
<A NAME="5953"></A>
<UL><PRE>// a class that incorrectly declares operator&gt;&gt; and
// operator&lt;&lt; as member functions
class String {
public:
  String(const char *value);
</PRE>
</UL><A NAME="5956"></A>
<UL><PRE>  ...
</PRE>
</UL><A NAME="5957"></A>
<UL><PRE>  istream&amp; operator&gt;&gt;(istream&amp; input);
  ostream&amp; operator&lt;&lt;(ostream&amp; output);
</PRE>
</UL><A NAME="16317"></A>
<UL><PRE>private:
  char *data;
};
</PRE>
</UL><A NAME="5958"></A>
<UL><PRE><A NAME="p88"></A>String s;
</PRE>
</UL><A NAME="5959"></A>
<UL><PRE>
s &gt;&gt; cin;                   // legal, but contrary
                            // to convention
</PRE>
</UL><A NAME="5960"></A>
<UL><PRE>
s &lt;&lt; cout;                  // ditto
</PRE>
</UL><A NAME="222852"></A>
<P><A NAME="dingp70"></A>
That would confuse everyone. As a result, these functions shouldn't be member functions. Notice that this is a different case from the one we discussed above. Here the goal is a natural calling syntax; earlier we were concerned about implicit type <NOBR>conversions.<SCRIPT>create_link(70);</SCRIPT>
</NOBR></P>
<A NAME="5962"></A>
<P><A NAME="dingp71"></A>
If you were designing these functions, you'd come up with something like <NOBR>this:<SCRIPT>create_link(71);</SCRIPT>
</NOBR></P>
<A NAME="5964"></A>
<UL><PRE>istream&amp; operator&gt;&gt;(istream&amp; input, String&amp; string)
{
  delete [] string.data;
</PRE>
</UL><A NAME="5965"></A>
<UL><PRE>  <I>read from input into some memory, and make string.data
  point to it</I>
</PRE>
</UL><A NAME="5966"></A>
<UL><PRE>  return input;
}
</PRE>
</UL><A NAME="5968"></A>
<UL><PRE>ostream&amp; operator&lt;&lt;(ostream&amp; output,
                    const String&amp; string)
{
  return output &lt;&lt; string.data;
}
</PRE>
</UL><A NAME="5969"></A>
<P><A NAME="dingp72"></A>
Notice that both functions need access to the <CODE>data</CODE> field of the <CODE>String</CODE> class, a field that's private. However, you already know that you have to make these functions non-members. You're boxed into a corner and have no choice: non-member functions with a need for access to non-public members of a class must be made friends of that <NOBR>class.<SCRIPT>create_link(72);</SCRIPT>
</NOBR></P>
<A NAME="5970"></A>
<P><A NAME="dingp73"></A>
The lessons of this Item are summarized below, in which it is assumed that <CODE>f</CODE> is the function you're trying to declare properly and <CODE>C</CODE> is the class to which it is conceptually <NOBR>related:<SCRIPT>create_link(73);</SCRIPT>
</NOBR></P><UL><A NAME="5971"></A>
<A NAME="dingp74"></A><LI><B>Virtual functions must be members.</B> If <CODE>f</CODE> needs to be virtual, make it a member function of <CODE>C</CODE>.<SCRIPT>create_link(74);</SCRIPT>

<A NAME="5972"></A>
<A NAME="dingp75"></A><LI><B><CODE>operator&gt;&gt;</CODE> and <CODE>operator&lt;&lt;</CODE> are never members.</B> If <CODE>f</CODE> is <CODE>operator&gt;&gt;</CODE> or <CODE>operator&lt;&lt;</CODE>, make <CODE>f</CODE> a non-member function. If, in addition, <CODE>f</CODE> needs access to non-public members of <CODE>C</CODE>, make <CODE>f</CODE> a friend of <CODE>C</CODE>.<SCRIPT>create_link(75);</SCRIPT>

<A NAME="30056"></A>
<A NAME="dingp76"></A><LI><A NAME="p89"></A><B>Only non-member functions get type conversions on their left-most argument.</B> If <CODE>f</CODE> needs type conversions on its left-most argument, make <CODE>f</CODE> a non-member function. If, in addition, <CODE>f</CODE> needs access to non-public members of <CODE>C</CODE>, make <CODE>f</CODE> a friend of <CODE>C</CODE>.<SCRIPT>create_link(76);</SCRIPT>

<A NAME="5974"></A>
<A NAME="dingp77"></A><LI><B>Everything else should be a member function.</B> If none of the other cases apply, make <CODE>f</CODE> a member function of <CODE>C</CODE>.<SCRIPT>create_link(77);</SCRIPT>


</UL>
<!-- SectionName="E20: Avoid data members in the public interface" -->
<A NAME="5976"></A><A NAME="5977"></A>

<DIV ALIGN="CENTER"><FONT SIZE="-1">Back to <A HREF="#5887">Item 19: Differentiate among member functions, non-member functions, and friend functions.</A>
                            <BR>Continue to <A HREF="#6003">Item 21: Use const whenever possible.</A></FONT></DIV>


<P><A NAME="dingp78"></A><FONT ID="eititle">Item 20: &nbsp;Avoid data members in the public interface.</FONT><SCRIPT>create_link(78);</SCRIPT>
</P>

<P><A NAME="dingp79"></A>
First, let's look at this issue from the point of view of consistency. If everything in the public interface is a function, clients of your class won't have to scratch their heads trying to remember whether to use parentheses when they want to access a member of your class. They'll just <I>do</I> it, because everything is a function. Over the course of a lifetime, that can save a lot of head <NOBR>scratching.<SCRIPT>create_link(79);</SCRIPT>
</NOBR></P>
<A NAME="5980"></A>
<P><A NAME="dingp80"></A>
You don't buy the consistency argument? How about the fact that using functions gives you much more precise control over the accessibility of data members? If you make a data member public, everybody has read/write access to it, but if you use functions to get and set its value, you can implement no access, read-only access, and read-write access. Heck, you can even implement write-only access if you want <NOBR>to:<SCRIPT>create_link(80);</SCRIPT>
</NOBR></P>
<A NAME="5983"></A>
<UL><PRE>class AccessLevels {
public:
  int getReadOnly() const{ return readOnly; }
</PRE>
</UL><A NAME="5988"></A>
<UL><PRE>  void setReadWrite(int value) { readWrite = value; }
  int getReadWrite() const { return readWrite; }
</PRE>
</UL><A NAME="5989"></A>
<UL><PRE>  void setWriteOnly(int value) { writeOnly = value; }
</PRE>
</UL><A NAME="16337"></A>
<UL><PRE>private:
  int noAccess;                    // no access to this   int
</PRE>
</UL><A NAME="16338"></A>
<UL><PRE>
  int readOnly;                    // read-only access to
                                   // this int
</PRE>
</UL><A NAME="16339"></A>
<UL><PRE>
  int readWrite;                   // read-write access to
                                   // this int
</PRE>
</UL><A NAME="16340"></A>
<UL><PRE>
  int writeOnly;                   // write-only access to
                                   // this int
};

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -