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

📄 ch19.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 4 页
字号:
17:&lt;&lt;&lt; Second run &gt;&gt;&gt;18: animal(int)  Destroyed an animal...19: animal(int)  Destroyed an animal...20: animal(int)  Destroyed an animal...21: Enter an offset (0-9) and a value. (-1 to stop): 0 022: Enter an offset (0-9) and a value. (-1 to stop): 1 123: Enter an offset (0-9) and a value. (-1 to stop): 2 224: Enter an offset (0-9) and a value. (-1 to stop): 3 325: animal(int)26: Destroyed an animal...27: animal(int)28: Destroyed an animal...29: animal(int)30: Destroyed an animal...31: initArray...32: [0] 033: [1] 134: [2] 235:36: animal array...37: [0] 038: [1] 1039: [2] 2040:41: Destroyed an animal...42: Destroyed an animal...43: Destroyed an animal...</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Listing 19.6 reproduces bothclasses in their entirety, so that you can see the creation and destruction of temporary<TT>Animal</TT> objects. The value of <TT>DefaultSize</TT> has been reduced to <TT>3</TT>to simplify the output.<BR>The <TT>Animal</TT> constructors and destructors on lines 33-48 each print a statementindicating when they are called.</P><P>On lines 74-81, the template behavior of an <TT>Array</TT> constructor is declared.On lines 114-118, the specialized constructor for an <TT>Array</TT> of <TT>Animal</TT>sis demonstrated. Note that in this special constructor, the default constructor isallowed to set the initial value for each <TT>Animal</TT>, and no explicit assignmentis done.</P><P>The first time this program is run, the first set of output is shown. Line 1 ofthe output shows the three default constructors called by creating the array. Theuser enters four numbers, and these are entered into the integer array.</P><P>Execution jumps to <TT>AnimalFillFunction()</TT>. Here a temporary <TT>Animal</TT>object is created on the heap on line 161, and its value is used to modify the <TT>Animal</TT>object in the array on line 162. On line 163, the temporary <TT>Animal</TT> is destroyed.This is repeated for each member of the array and is reflected in the output on line6.</P><P>At the end of the program, the arrays are destroyed, and when their destructorsare called, all their objects are destroyed as well. This is reflected in the outputon line 16.</P><P>For the second set of output (lines 18-43), the special implementation of thearray of character constructor, shown on lines 114-118 of the program, is commentedout. When the program is run again, the <TT>template</TT> constructor, shown on lines74-81 of the program, is run when the <TT>Animal</TT> array is constructed.</P><P>This causes temporary <TT>Animal</TT> objects to be called for each member ofthe array on lines 79 and 80 of the program, and is reflected in the output on lines18 to 20 of the output.</P><P>In all other respects, the output for the two runs is identical, as you wouldexpect.<H4 ALIGN="CENTER"><A NAME="Heading27"></A><FONT COLOR="#000077">Static Members andTemplates</FONT></H4><P>A template can declare static data members. Each instantiation of the templatethen has its own set of static data, one per class type. That is, if you add a staticmember to the <TT>Array</TT> class (for example, a counter of how many arrays havebeen created), you will have one such member per type: one for all the arrays of<TT>Animal</TT>s, and another for all the arrays of integers. Listing 19.7 adds astatic member and a static function to the <TT>Array</TT> class.</P><P><A NAME="Heading28"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 19.7. Usingstatic member data and functions with templates.</B></FONT><PRE><FONT COLOR="#0066FF">1:     #include &lt;iostream.h&gt;2:3:     template &lt;class T&gt;  // declare the template and the parameter4:     class Array            // the class being parameterized5:     {6:     public:7:        // constructors8:        Array(int itsSize = DefaultSize);9:        Array(const Array &amp;rhs);10:       ~Array() { delete [] pType;   itsNumberArrays--; }11:12:       // operators13:       Array&amp; operator=(const Array&amp;);14:       T&amp; operator[](int offSet) { return pType[offSet]; }15:       const T&amp; operator[](int offSet) const 16:          { return pType[offSet]; }17:       // accessors18:       int GetSize() const { return itsSize; }19:       static int GetNumberArrays() { return itsNumberArrays; }20:21:       // friend function22:      friend ostream&amp; operator&lt;&lt; (ostream&amp;, const Array&lt;T&gt;&amp;);23:24:    private:25:       T *pType;26:       int  itsSize;27:       static int itsNumberArrays;28:    };29:30:    template &lt;class T&gt;31:       int Array&lt;T&gt;::itsNumberArrays = 0;32:33:    template &lt;class T&gt;34:    Array&lt;T&gt;::Array(int size = DefaultSize):35:    itsSize(size)36:    {37:       pType = new T[size];38:       for (int i = 0; i&lt;size; i++)39:         pType[i] = (T)0;40:       itsNumberArrays++;41:    }42:43:    template &lt;class T&gt;44:    Array&lt;T&gt;&amp; Array&lt;T&gt;::operator=(const Array &amp;rhs)45:    {46:       if (this == &amp;rhs)47:          return *this;48:       delete [] pType;49:       itsSize = rhs.GetSize();50:       pType = new T[itsSize];51:       for (int i = 0; i&lt;itsSize; i++)52:          pType[i] = rhs[i];53:    }54:55:    template &lt;class T&gt;56:    Array&lt;T&gt;::Array(const Array &amp;rhs)57:    {58:       itsSize = rhs.GetSize();59:       pType = new T[itsSize];60:       for (int i = 0; i&lt;itsSize; i++)61:          pType[i] = rhs[i];62:       itsNumberArrays++;63:    }64:65:66:    template &lt;class T&gt;67:    ostream&amp; operator&lt;&lt; (ostream&amp; output, const Array&lt;T&gt;&amp; theArray)68:    {69:       for (int i = 0; i&lt;theArray.GetSize(); i++)70:          output &lt;&lt; &quot;[&quot; &lt;&lt; i &lt;&lt; &quot;] &quot; &lt;&lt; theArray[i] &lt;&lt; endl;71:       return output;72:    }73:74:75:    Array&lt;Animal&gt;::Array(int AnimalArraySize):76:    itsSize(AnimalArraySize)77:    {78:       pType = new T[AnimalArraySize];79:       itsNumberArrays++;80:    }81:82:    int main()83:    {84:85:       cout &lt;&lt; Array&lt;int&gt;::GetNumberArrays() &lt;&lt; &quot; integer arrays\n&quot;;86:       cout &lt;&lt; Array&lt;Animal&gt;::GetNumberArrays();87        cout &lt;&lt; &quot; animal arrays\n\n&quot;;88:       Array&lt;int&gt; intArray;89:       Array&lt;Animal&gt; animalArray;90:91:       cout &lt;&lt; intArray.GetNumberArrays() &lt;&lt; &quot; integer arrays\n&quot;;92:       cout &lt;&lt; animalArray.GetNumberArrays();93:       cout &lt;&lt; &quot; animal arrays\n\n&quot;;93:94:       Array&lt;int&gt; *pIntArray = new Array&lt;int&gt;;95:96:       cout &lt;&lt; Array&lt;int&gt;::GetNumberArrays() &lt;&lt; &quot; integer arrays\n&quot;;97:       cout &lt;&lt; Array&lt;Animal&gt;::GetNumberArrays();98:       cout &lt;&lt; &quot; animal arrays\n\n&quot;;98:99:       delete pIntArray;100:101:      cout &lt;&lt; Array&lt;int&gt;::GetNumberArrays() &lt;&lt; &quot; integer arrays\n&quot;;102:      cout &lt;&lt; Array&lt;Animal&gt;::GetNumberArrays();103:      cout &lt;&lt; &quot; animal arrays\n\n&quot;;103:     return 0;<TT>104: }</TT></FONT><FONT COLOR="#0066FF">Output: 0 integer arrays0 animal arrays1 integer arrays1 animal arrays2 integer arrays1 animal arrays1 integer arrays1 animal arrays</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The declaration of the <TT>Animal</TT>class has been left out to save space. The <TT>Array</TT> class has added the staticvariable <TT>itsNumberArrays</TT> on line 27, and because this data is private, thestatic public accessor <TT>GetNumberArrays()</TT> was added on line 19.<BR>Initialization of the static data is accomplished with a full template qualification,as shown on lines 30 and 31. The constructors of <TT>Array</TT> and the destructorare each modified to keep track of how many arrays exist at any moment.</P><P>Accessing the static members is exactly like accessing the static members of anyclass: You can do so with an existing object, as shown on lines 91 and 92, or byusing the full class specification, as shown on lines 85 and 86. Note that you mustuse a specific type of array when accessing the static data. There is one variablefor each type.<BLOCKQUOTE>	<P><HR><B>DO</B> use statics with templates as needed.<B> DO</B> specialize template behavior	by overriding template functions by type.<B> DO</B> use the parameters to template	functions to narrow their instances to be type-safe. <HR></BLOCKQUOTE><H3 ALIGN="CENTER"><A NAME="Heading30"></A><FONT COLOR="#000077">The Standard TemplateLibrary</FONT></H3><P>A new development in C++ is the adoption of the Standard Template Library (STL).All the major compiler vendors now offer the STL as part of their compilers. STLis a library of template-based container classes, including vectors, lists, queues,and stacks. The STL also includes a number of common algorithms, including sortingand searching.</P><P>The goal of the STL is to give you an alternative to reinventing the wheel forthese common requirements. The STL is tested and debugged, offers high performance,and is free. Most important, the STL is reusable; once you understand how to usean STL container, you can use it in all your programs without reinventing it.<H3 ALIGN="CENTER"><A NAME="Heading31"></A><FONT COLOR="#000077">Summary</FONT></H3><P>Today you learned how to create and use templates. Templates are a built-in facilityof C++, used to create parameterized types--types that change their behavior basedon parameters passed in at creation. They are a way to reuse code safely and effectively.</P><P>The definition of the template determines the parameterized type. Each instanceof the template is an actual object, which can be used like any other object--asa parameter to a function, as a return value, and so forth.</P><P>Template classes can declare three types of friend functions: non-template, generaltemplate, and type-specific template. A template can declare static data members,in which case each instance of the template has its own set of static data.</P><P>If you need to specialize behavior for some template functions based on the actualtype, you can override a template function with a particular type. This works formember functions as well.<H3 ALIGN="CENTER"><A NAME="Heading32"></A><FONT COLOR="#000077">Q&amp;A</FONT></H3><DL>	<DD><B>Q. Why use templates when macros will do?<BR>	</B><BR>	<B>A. </B>Templates are type-safe and built into the language.<BR>	<BR>	<B>Q. What is the difference between the parameterized type of a template function	and the parameters to a normal function?<BR>	</B><BR>	<B>A.</B> A regular function (non-template) takes parameters on which it may take	action. A template function allows you to parameterize the type of a particular parameter	to the function. That is, you can pass an <TT>Array</TT> of Type to a function, and	then have the Type determined by the template instance.<BR>	<BR>	<B>Q. When do you use templates and when do you use inheritance?<BR>	</B><BR>	<B>A.</B> Use templates when all the behavior, or virtually all the behavior, is	unchanged, except in regard to the type of the item on which your class acts. If	you find yourself copying a class and changing only the type of one or more of its	members, it may be time to consider using a template.<BR>	<BR>	<B>Q. When do you use general template friend classes?<BR>	</B><BR>	<B>A.</B> When every instance, regardless of type, should be a friend to this class	or function.<BR>	<BR>	<B>Q. When do you use type-specific template friend classes or functions?<BR>	</B><BR>	<B>A.</B> When you want to establish a one-to-one relationship between two classes.	For example, <TT>array&lt;int&gt;</TT> should match <TT>iterator&lt;int&gt;</TT>,	but not <TT>iterator&lt;Animal&gt;</TT>.</DL><H3 ALIGN="CENTER"><A NAME="Heading33"></A><FONT COLOR="#000077">Workshop</FONT></H3><P>The Workshop provides quiz questions to help you solidify your understanding ofthe material covered, and exercises to provide you with experience in using whatyou've learned. Try to answer the quiz and exercise questions before checking theanswers in Appendix D, and make sure you understand the answers before continuingto the next chapter.<H4 ALIGN="CENTER"><A NAME="Heading34"></A><FONT COLOR="#000077">Quiz</FONT></H4><DL>	<DD><B>1.</B> What is the difference between a template and a macro?<BR>	<B><BR>	2.</B> What is the difference between the parameter in a template and the parameter	in a function?<BR>	<B><BR>	3.</B> What is the difference between a type-specific template friend class and a	general template friend class?<BR>	<B><BR>	4.</B> Is it possible to provide special behavior for one instance of a template	but not for other instances?<BR>	<B><BR>	5.</B> How many static variables are created if you put one static member into a	template class definition?</DL><H4 ALIGN="CENTER"><A NAME="Heading35"></A><FONT COLOR="#000077">Exercises</FONT></H4><DL>	<DD><B>1.</B> Create a template based on this <TT>List</TT> class:</DL><PRE><FONT COLOR="#0066FF">class List{private:public:     List():head(0),tail(0),theCount(0) {}     virtual ~List();     void insert( int value );     void append( int value );     int is_present( int value ) const;     int is_empty() const { return head == 0; }     int count() const { return theCount; }private:     class ListCell     {     public:          ListCell(int value, ListCell *cell =):val(value),next(cell){}          int val;          ListCell *next;     };     ListCell *head;     ListCell *tail;     int theCount;};</FONT></PRE><DL>	<DD><B>2. </B>Write the implementation for the <TT>List</TT> class (non-template)	version.<BR>	<B><BR>	3.</B> Write the template version of the implementations.<BR>	<B><BR>	4.</B> Declare three list objects: a list of <TT>String</TT>s, a list of <TT>Cat</TT>s,	and a list of <TT>int</TT>s.<BR>	<B><BR>	5.</B> BUG BUSTERS: What is wrong with the following code? (Assume the <TT>List</TT>	template is defined and <TT>Cat</TT> is the class defined earlier in the book.)</DL><PRE><FONT COLOR="#0066FF">List&lt;Cat&gt; Cat_List;Cat Felix;CatList.append( Felix );cout &lt;&lt; &quot;Felix is &quot; &lt;&lt;     ( Cat_List.is_present( Felix ) ) ? &quot;&quot; : &quot;not &quot; &lt;&lt; &quot;present\n&quot;;</FONT></PRE><DL>	<DD>HINT (this is tough): What makes <TT>Cat</TT> different from <TT>int</TT>?<BR>	<BR>	<B>6.</B> Declare friend <TT>operator==</TT> for <TT>List</TT>.<BR>	<B><BR>	7.</B> Implement friend <TT>operator==</TT> for <TT>List</TT>.<BR>	<B><BR>	8.</B> Does <TT>operator==</TT> have the same problem as in Exercise 5?<BR>	<B><BR>	9.</B> Implement a template function for <TT>swap</TT>, which exchanges two variables.	<P></DL><P ALIGN="CENTER"><A HREF="ch18.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch18.htm"><IMG SRC="BLANPREV.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANPREV.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="tppmsgs/msgs0.htm#1" tppabs="http://www.mcp.com/sams"><IMGSRC="BLANHOME.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANHOME.GIF" WIDTH="37" HEIGHT="37" ALIGN="BOTTOM"BORDER="0"></A><A HREF="index.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/index.htm"><IMG SRC="BLANTOC.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANTOC.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="ch20.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch20.htm"><IMG SRC="BLANNEXT.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANNEXT.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A><A HREF="#heading1"><IMG SRC="BLANTOP.GIF" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/buttons/BLANTOP.GIF"WIDTH="37" HEIGHT="37" ALIGN="BOTTOM" BORDER="0"></A></BODY></HTML>

⌨️ 快捷键说明

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