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

📄 ch19.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 4 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD><!-- This document was created from RTF source by rtftohtml version 3.0.1 -->	<META NAME="GENERATOR" Content="Symantec Visual Page 1.0">	<META HTTP-EQUIV="Content-Type" CONTENT="text/html;CHARSET=iso-8859-1">	<TITLE>Teach Yourself C++ in 21 Days</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><H1 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></H1><H1></H1><UL>	<LI><A HREF="#Heading1">Day 19</A>	<UL>		<LI><A HREF="#Heading2">Templates</A>		<UL>			<LI><A HREF="#Heading3">What Are Templates?</A>			<LI><A HREF="#Heading4">Parameterized Types</A>			<LI><A HREF="#Heading5">Template Definition</A>			<LI><A HREF="#Heading6">Listing 19.1. A template of an Array class</A><A HREF="#Heading7">.</A>			<UL>				<LI><A HREF="#Heading8">Using the Name</A>				<LI><A HREF="#Heading9">Implementing the Template</A>			</UL>			<LI><A HREF="#Heading10">Listing 19.2. The implementation of the template array</A><A			HREF="#Heading11">.</A>			<LI><A HREF="#Heading12">Template Functions</A>			<LI><A HREF="#Heading13">Templates and Friends</A>			<UL>				<LI><A HREF="#Heading14">Non-Template Friend Classes and Functions</A>			</UL>			<LI><A HREF="#Heading15">Listing 19.3. Non-template friend function</A><A HREF="#Heading16">.</A>			<UL>				<LI><A HREF="#Heading17">General Template Friend Class or Function</A>			</UL>			<LI><A HREF="#Heading18">Listing 19.4. Using operator ostream</A><A HREF="#Heading19">.</A>			<UL>				<LI><A HREF="#Heading20">A Type-Specific Template Friend Class or Function</A>			</UL>			<LI><A HREF="#Heading21">Using Template Items</A>			<LI><A HREF="#Heading22">Listing 19.5. Passing template objects</A>			<LI><A HREF="#Heading23">to and from functions.</A>			<UL>				<LI><A HREF="#Heading24">Specialized Functions</A>			</UL>			<LI><A HREF="#Heading25">Listing 19.6. Specializing template implementations</A><A			HREF="#Heading26">.</A>			<UL>				<LI><A HREF="#Heading27">Static Members and Templates</A>			</UL>			<LI><A HREF="#Heading28">Listing 19.7. Using static member data and functions</A>			<LI><A HREF="#Heading29">with templates.</A>			<LI><A HREF="#Heading30">The Standard Template Library</A>			<LI><A HREF="#Heading31">Summary</A>			<LI><A HREF="#Heading32">Q&amp;A</A>			<LI><A HREF="#Heading33">Workshop</A>			<UL>				<LI><A HREF="#Heading34">Quiz</A>				<LI><A HREF="#Heading35">Exercises</A>			</UL>		</UL>	</UL></UL><P><HR SIZE="4"><H2 ALIGN="CENTER"><A NAME="Heading1"></A><FONT COLOR="#000077">Day 19</FONT></H2><H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">Templates</FONT></H2><P>On Day 17, &quot;The Preprocessor,&quot; you saw how to use macros to create variouslists using the concatenation operator. Macros have a number of problems that arefixed by templates.</P><P>Today you will learn<UL>	<LI>What templates are and how to use them.	<P>	<LI>Why templates supply a better alternative to macros.	<P>	<LI>How to create class templates.	<P>	<LI>How to create function templates.</UL><H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">What Are Templates?</FONT></H3><P>At the end of Week 2, you saw how to build a <TT>PartsList</TT> object and howto use it to create a <TT>PartsCatalog</TT>. If you want to build on the <TT>PartsList</TT>object to make a list of cats, you have a problem: <TT>PartsList</TT> only knowsabout parts.</P><P>To solve this problem, you can create a <TT>List</TT> base class and derive fromit the <TT>PartsList</TT> and <TT>CatsList</TT> classes. You could then cut and pastemuch of the <TT>PartsList</TT> class into the new <TT>CatsList</TT> declaration.Next week, when you want to make a list of <TT>Car</TT> objects, you would then haveto make a new class, and again you'd cut and paste.</P><P>Needless to say, this is not a satisfactory solution. Over time, the <TT>List</TT>class and its derived classes will have to be extended. Making sure that all thechanges are propagated to all the related classes would be a nightmare.</P><P>On Day 17, one approach to parameterizing lists was demonstrated briefly--usingmacros and name concatenation. Although macros do save much of the cutting and pasting,they have one killer disadvantage: Like everything else in the preprocessor, theyare not type-safe.</P><P>Templates offer the preferred method of creating parameterized lists in C++. Theyare an integrated part of the language, they are type-safe, and they are very flexible.<H3 ALIGN="CENTER"><A NAME="Heading4"></A><FONT COLOR="#000077">Parameterized Types</FONT></H3><P>Templates allow you to teach the compiler how to make a list of any type of thing,rather than creating a set of type-specific lists--a <TT>PartsList</TT> is a listof parts, a <TT>CatList</TT> is a list of cats. The only way in which they differis the type of the thing on the list. With templates, the type of the thing on thelist becomes a parameter to the definition of the class.</P><P>A common component of virtually all C++ libraries is an array class. As you sawwith <TT>Lists</TT>, it is tedious and inefficient to create one array class forintegers, another for doubles, and yet another for an array of <TT>Animal</TT>s.Templates let you declare a parameterized array class and then specify what typeof object each instance of the array will hold.</P><DL>	<DD><HR><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B><I>Instantiation</I> is the	act of creating a specific type from a template. The individual classes are called	instances of the template. <HR></DL><P>Parameterized templates provide you with the ability to create a general class,and pass types as parameters to that class, in order to build specific instances.<H3 ALIGN="CENTER"><A NAME="Heading5"></A><FONT COLOR="#000077">Template Definition</FONT></H3><P>You declare a parameterized <TT>Array</TT> object (a template for an array) bywriting</P><PRE><FONT COLOR="#0066FF">1: template &lt;class T&gt;    // declare the template and the parameter2: class Array           // the class being parameterized3: {4:    public:5:      Array();6:   // full class declaration here7: };</FONT></PRE><P>The keyword <TT>template</TT> is used at the beginning of every declaration anddefinition of a template class. The parameters of the template are after the keyword<TT>template</TT>. The parameters are the things that will change with each instance.For example, in the array template shown previously, the type of the objects storedin the array will change. One instance might store an array of integers, while anothermight store an array of <TT>Animals</TT>.</P><P>In this example, the keyword <TT>class</TT> is used, followed by the identifier<TT>T</TT>. The keyword <TT>class</TT> indicates that this parameter is a type. Theidentifier <TT>T</TT> is used throughout the rest of the template definition to referto the parameterized type. One instance of this class will substitute <TT>int</TT>everywhere <TT>T</TT> appears, and another will substitute <TT>Cat</TT>.</P><P>To declare an <TT>int</TT> and a <TT>Cat</TT> instance of the parameterized <TT>Array</TT>class, you would write</P><PRE><FONT COLOR="#0066FF">Array&lt;int&gt; anIntArray;Array&lt;Cat&gt; aCatArray;</FONT></PRE><P>The object <TT>anIntArray</TT> is of the type array of integers; the object <TT>aCatArray</TT>is of the type array of cats. You can now use the type <TT>Array&lt;int&gt;</TT>anywhere you would normally use a type--as the return value from a function, as aparameter to a function, and so forth. Listing 19.1 provides the full declarationof this stripped-down <TT>Array</TT> template.<BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Listing 19.1 is not a complete program!	<HR></BLOCKQUOTE><P><A NAME="Heading6"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 19.1. A templateof an Array class</B></FONT><PRE><FONT COLOR="#0066FF">1: Listing 19.1 A template of an array class2:     #include &lt;iostream.h&gt;3:     const int DefaultSize = 10;4:5:     template &lt;class T&gt;  // declare the template and the parameter6:     class Array            // the class being parameterized7:     {8:     public:9:        // constructors10:       Array(int itsSize = DefaultSize);11:       Array(const Array &amp;rhs);12:       ~Array() { delete [] pType; }13:14:       // operators15:       Array&amp; operator=(const Array&amp;);16:       T&amp; operator[](int offSet) { return pType[offSet]; }17:18:       // accessors19:       int getSize() { return itsSize; }20:21:    private:22:       T *pType;23:       int  itsSize;</FONT><TT></TT><FONT COLOR="#0066FF"><TT>24: };</TT> </FONT></PRE><DL>	<DD><HR><FONT COLOR="#000077"><B>Output:</B></FONT><B> </B>There is no output. This is an	incomplete program. <HR></DL><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>The definition of the templatebegins on line 5, with the keyword <TT>template</TT> followed by the parameter. Inthis case, the parameter is identified to be a type by the keyword <TT>class</TT>,and the identifier <TT>T</TT> is used to represent the parameterized type.</P><P>From line 6 until the end of the template on line 24, the rest of the declarationis like any other class declaration. The only difference is that wherever the typeof the object would normally appear, the identifier <TT>T</TT> is used instead. Forexample, <TT>operator[]</TT> would be expected to return a reference to an objectin the array, and in fact it is declared to return a reference to a <TT>T</TT>.</P><P>When an instance of an integer array is declared, the <TT>operator=</TT> thatis provided to that array will return a reference to an integer. When an instanceof an <TT>Animal</TT> array is declared, the <TT>operator=</TT> provided to the <TT>Animal</TT>array will return a reference to an <TT>Animal</TT>.<H4 ALIGN="CENTER"><A NAME="Heading8"></A><FONT COLOR="#000077">Using the Name</FONT></H4><P>Within the class declaration, the word <TT>Array</TT> may be used without furtherqualification. Elsewhere in the program, this class will be referred to as <TT>Array&lt;T&gt;</TT>.For example, if you do not write the constructor within the class declaration, youmust write</P><PRE><FONT COLOR="#0066FF">template &lt;class T&gt;Array&lt;T&gt;::Array(int size):itsSize = size{pType = new T[size];for (int i = 0; i&lt;size; i++)pType[i] = 0;}</FONT></PRE><P>The declaration on the first line of this code fragment is required to identifythe type (<TT>class T</TT>). The template name is <TT>Array&lt;T&gt;</TT>, and thefunction name is <TT>Array(int size)</TT>.</P><P>The remainder of the function is exactly the same as it would be for a non-templatefunction. It is a common and preferred method to get the class and its functionsworking as a simple declaration before turning it into a template.<H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">Implementing theTemplate</FONT></H4><P>The full implementation of the <TT>Array</TT> template class requires implementationof the copy constructor, <TT>operator=</TT>, and so forth. Listing 19.2 providesa simple driver program to exercise this template class.<DL>	<DD><HR><FONT COLOR="#000077"><B><BR>	NOTE:</B></FONT><B> </B>Some older compilers do not support templates. Templates	are, however, part of the emerging C++ standard. All major compiler vendors have	committed to supporting templates in their next release, if they have not already	done so. If you have an older compiler, you won't be able to compile and run the	exercises in this chapter. It's still a good idea to read through the entire chapter,	however, and return to this material when you upgrade your compiler. <HR></DL><P><A NAME="Heading10"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 19.2. The implementationof the template array.</B></FONT><PRE><FONT COLOR="#0066FF">1:     #include &lt;iostream.h&gt;2:3:     const int DefaultSize = 10;4:5:     // declare a simple Animal class so that we can6:     // create an array of animals7:8:     class Animal9:     {10:    public:11:       Animal(int);12:       Animal();13:       ~Animal() {}14:       int GetWeight() const { return itsWeight; }15:       void Display() const { cout &lt;&lt; itsWeight; }16:    private:17:       int itsWeight;18:    };19:20:    Animal::Animal(int weight):21:    itsWeight(weight)22:    {}23:24:    Animal::Animal():25:    itsWeight(0)26:    {}27:28:29:    template &lt;class T&gt;  // declare the template and the parameter30:    class Array            // the class being parameterized31:    {32:    public:33:       // constructors34:       Array(int itsSize = DefaultSize);35:       Array(const Array &amp;rhs);36:       ~Array() { delete [] pType; }37:38:       // operators39:       Array&amp; operator=(const Array&amp;);40:       T&amp; operator[](int offSet) { return pType[offSet]; }41:       const T&amp; operator[](int offSet) const 42:           { return pType[offSet]; }43:       // accessors44:       int GetSize() const { return itsSize; }45:46:    private:47:       T *pType;48:       int  itsSize;49:    };50:51:    // implementations follow...52:53:    // implement the Constructor54:    template &lt;class T&gt;55:    Array&lt;T&gt;::Array(int size = DefaultSize):56:    itsSize(size)57:    {58:       pType = new T[size];59:       for (int i = 0; i&lt;size; i++)60:          pType[i] = 0;61:    }62:63:    // copy constructor64:    template &lt;class T&gt;65:    Array&lt;T&gt;::Array(const Array &amp;rhs)66:    {67:       itsSize = rhs.GetSize();68:       pType = new T[itsSize];69:       for (int i = 0; i&lt;itsSize; i++)70:          pType[i] = rhs[i];71:    }72:73:    // operator=74:    template &lt;class T&gt;75:    Array&lt;T&gt;&amp; Array&lt;T&gt;::operator=(const Array &amp;rhs)76:    {77:       if (this == &amp;rhs)78:          return *this;79:       delete [] pType;80:       itsSize = rhs.GetSize();81:       pType = new T[itsSize];82:       for (int i = 0; i&lt;itsSize; i++)83:          pType[i] = rhs[i];84:       return *this;85:    }86:87:    // driver program88:    int main()89:    {90:       Array&lt;int&gt; theArray;      // an array of integers91:       Array&lt;Animal&gt; theZoo;     // an array of Animals92:       Animal *pAnimal;93:94:       // fill the arrays95:       for (int i = 0; i &lt; theArray.GetSize(); i++)96:       {97:          theArray[i] = i*2;98:          pAnimal = new Animal(i*3);99:          theZoo[i] = *pAnimal;100:            delete pAnimal;101:      }102:      // print the contents of the arrays103:      for (int j = 0; j &lt; theArray.GetSize(); j++)104:      {105:         cout &lt;&lt; &quot;theArray[&quot; &lt;&lt; j &lt;&lt; &quot;]:\t&quot;;106:         cout &lt;&lt; theArray[j] &lt;&lt; &quot;\t\t&quot;;

⌨️ 快捷键说明

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