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

📄 ch08.htm

📁 一本好的VC学习书,本人就是使用这本书开始学习的vc,希望能对大家有帮助
💻 HTM
📖 第 1 页 / 共 5 页
字号:
<!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="ch07rv1.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch07rv1.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="ch09.htm" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/htm/ch09.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 8</A>	<UL>		<LI><A HREF="#Heading2">Pointers</A>		<UL>			<LI><A HREF="#Heading3">What Is a Pointer?</A>			<UL>				<LI><A HREF="#Heading4">Figure 8.1.</A>			</UL>			<LI><A HREF="#Heading5">Listing 8.1. Demonstrating address of variables</A>			<UL>				<LI><A HREF="#Heading7">Figure 8.2.</A>			</UL>			<LI><A HREF="#Heading8">Storing the Address in a Pointer</A>			<UL>				<LI><A HREF="#Heading9">Pointer Names</A>				<LI><A HREF="#Heading10">The Indirection Operator</A>				<LI><A HREF="#Heading11">Pointers, Addresses, and Variables</A>				<UL>					<LI><A HREF="#Heading12">Figure 8.3.</A>				</UL>				<LI><A HREF="#Heading13">Manipulating Data by Using Pointers</A>			</UL>			<LI><A HREF="#Heading14">Listing 8.2. Manipulating data by using pointers</A>			<UL>				<LI><A HREF="#Heading16">Examining the Address</A>			</UL>			<LI><A HREF="#Heading17">Listing 8.3. Finding out what is stored in pointers</A>			<LI><A HREF="#Heading19">Pointers</A>			<LI><A HREF="#Heading20">Why Would You Use Pointers?</A>			<LI><A HREF="#Heading21">The Stack and the Free Store</A>			<UL>				<LI><A HREF="#Heading22">new</A>				<LI><A HREF="#Heading23">delete</A>			</UL>			<LI><A HREF="#Heading24">Listing 8.4. Allocating, using, and deleting pointers.</A>			<LI><A HREF="#Heading25">Memory Leaks</A>			<LI><A HREF="#Heading26">Creating Objects on the Free Store</A>			<LI><A HREF="#Heading27">Deleting Objects</A>			<LI><A HREF="#Heading28">Listing 8.5. Creating and deleting objects on the free store</A>			<LI><A HREF="#Heading30">Accessing Data Members</A>			<LI><A HREF="#Heading31">Listing 8.6. Accessing member data of objects</A>			<LI><A HREF="#Heading32">on the free store.</A>			<LI><A HREF="#Heading33">Member Data on the Free Store</A>			<LI><A HREF="#Heading34">Listing 8.7. Pointers as member data</A>			<LI><A HREF="#Heading36">The this Pointer</A>			<LI><A HREF="#Heading37">Listing 8.8. Using the this pointer</A>			<LI><A HREF="#Heading39">Stray or Dangling Pointers</A>			<LI><A HREF="#Heading40">Listing 8.9. Creating a stray pointer</A>			<LI><A HREF="#Heading42">const Pointers</A>			<UL>				<LI><A HREF="#Heading43">const Pointers and const Member Functions</A>			</UL>			<LI><A HREF="#Heading44">Listing 8.10. Using pointers to const objects</A>			<UL>				<LI><A HREF="#Heading46">const this Pointers</A>			</UL>			<LI><A HREF="#Heading47">Summary</A>			<LI><A HREF="#Heading48">Q&amp;A</A>			<LI><A HREF="#Heading49">Workshop</A>			<UL>				<LI><A HREF="#Heading50">Quiz</A>				<LI><A HREF="#Heading51">Exercises</A>			</UL>		</UL>	</UL></UL><P><HR SIZE="4"><H2 ALIGN="CENTER"><A NAME="Heading1"></A><FONT COLOR="#000077">Day 8</FONT></H2><H2 ALIGN="CENTER"><A NAME="Heading2"></A><FONT COLOR="#000077">Pointers</FONT></H2><P>One of the most powerful tools available to a C++ programmer is the ability tomanipulate computer memory directly by using pointers. Today you will learn<UL>	<LI>What pointers are.	<P>	<LI>How to declare and use pointers.	<P>	<LI>What the free store is and how to manipulate memory.</UL><P>Pointers present two special challenges when learning C++: They can be somewhatconfusing, and it isn't immediately obvious why they are needed. This chapter explainshow pointers work, step by step. You will fully understand the need for pointers,however, only as the book progresses.<H3 ALIGN="CENTER"><A NAME="Heading3"></A><FONT COLOR="#000077">What Is a Pointer?</FONT></H3><DL>	<DD><HR><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>pointer</I> is a variable	that holds a memory address. <HR></DL><P>To understand pointers, you must know a little about computer memory. Computermemory is divided into sequentially numbered memory locations. Each variable is locatedat a unique location in memory, known as its address. (This is discussed in the &quot;ExtraCredit&quot; section following Day 5, &quot;Functions.&quot;) Figure 8.1 shows aschematic representation of the storage of an <TT>unsigned long</TT> integer variable<TT>theAge</TT>.<BR><BR><A NAME="Heading4"></A><A HREF="figure1.jpg" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/art/ch08/figure1.jpg"><FONT COLOR="#000077">Figure8.1.</FONT></A><I> A schematic representation of <TT>theAge</TT></I>.<BR><BR>Different computers number this memory using different, complex schemes. Usuallyprogrammers don't need to know the particular address of any given variable, becausethe compiler handles the details. If you want this information, though, you can usethe <TT>address of</TT> operator (<TT>&amp;</TT>), which is illustrated in Listing8.1.</P><P><A NAME="Heading5"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 8.1. Demonstratingaddress of variables.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:   // Listing 8.1 Demonstrates address of operator2:   // and addresses of local variables3:4:   #include &lt;iostream.h&gt;5:6:   int main()7:   {8:      unsigned short shortVar=5;9:      unsigned long  longVar=65535;10:     long sVar = -65535;11:12:     cout &lt;&lt; &quot;shortVar:\t&quot; &lt;&lt; shortVar;13:     cout &lt;&lt; &quot; Address of shortVar:\t&quot;;14:     cout &lt;&lt;  &amp;shortVar  _&lt;&lt; &quot;\n&quot;;15:16:     cout &lt;&lt; &quot;longVar:\t&quot;  &lt;&lt; longVar;17:      cout  &lt;&lt; &quot; Address of longVar:\t&quot; ;18:      cout &lt;&lt;  &amp;longVar  _&lt;&lt; &quot;\n&quot;;19:20:     cout &lt;&lt; &quot;sVar:\t&quot;     &lt;&lt; sVar;21:       cout     &lt;&lt; &quot; Address of sVar:\t&quot; ;22:       cout     &lt;&lt;  &amp;sVar     _&lt;&lt; &quot;\n&quot;;23:24:  return 0;<TT>25: }</TT></FONT><FONT COLOR="#0066FF">Output: shortVar: 5       Address of shortVar: 0x8fc9:fff4longVar:  65535   Address of longVar:  0x8fc9:fff2sVar:    -65535   Address of sVar:     0x8fc9:ffee</FONT></PRE><P>(Your printout may look different.)</P><P><BR><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Three variables are declaredand initialized: a <TT>short</TT> in line 8, an <TT>unsigned long</TT> in line 9,and a <TT>long</TT> in line 10. Their values and addresses are printed in lines 12-16,by using the <TT>address of</TT> operator (<TT>&amp;</TT>).<BR>The value of <TT>shortVar</TT> is <TT>5</TT>, as expected, and its address is <TT>0x8fc9:fff4</TT>when run on my 80386-based computer. This complicated address is computer-specificand may change slightly each time the program is run. Your results will be different.What doesn't change, however, is that the difference in the first two addresses istwo bytes if your computer uses two-byte <TT>short</TT> integers. The differencebetween the second and third is four bytes if your computer uses four-byte <TT>long</TT>integers. Figure 8.2 illustrates how the variables in this program would be storedin memory.<BR><BR><A NAME="Heading7"></A><A HREF="figure2.jpg" tppabs="http://www.mcp.com/814147200/0-672/0-672-31070-8/art/ch08/figure2.jpg"><FONT COLOR="#000077">Figure8.2.</FONT></A><FONT COLOR="#000077"><I> </I></FONT><I>Illustration of variable storage.</I><BR><BR>There is no reason why you need to know the actual numeric value of the address ofeach variable. What you care about is that each one has an address and that the rightamount of memory is set aside. You tell the compiler how much memory to allow foryour variables by declaring the variable type; the compiler automatically assignsan address for it. For example, a <TT>long</TT> integer is typically four bytes,meaning that the variable has an address to four bytes of memory.<H4 ALIGN="CENTER"><A NAME="Heading8"></A><FONT COLOR="#000077">Storing the Addressin a Pointer</FONT></H4><P>Every variable has an address. Even without knowing the specific address of agiven variable, you can store that address in a pointer.</P><P>For example, suppose that <TT>howOld</TT> is an integer. To declare a pointercalled <TT>pAge</TT> to hold its address, you would write</P><PRE><FONT COLOR="#0066FF">int *pAge = 0;</FONT></PRE><P>This declares <TT>pAge</TT> to be a pointer to <TT>int</TT>. That is, <TT>pAge</TT>is declared to hold the address of an <TT>int</TT>.</P><P>Note that <TT>pAge</TT> is a variable like any of the variables. When you declarean integer variable (type <TT>int</TT>), it is set up to hold an integer. When youdeclare a pointer variable like <TT>pAge</TT>, it is set up to hold an address. <TT>pAge</TT>is just a different type of variable.</P><P>In this example, <TT>pAge</TT> is initialized to zero. A pointer whose value iszero is called a null pointer. All pointers, when they are created, should be initializedto something. If you don't know what you want to assign to the pointer, assign <TT>0</TT>.A pointer that is not initialized is called a wild pointer. Wild pointers are verydangerous.<BLOCKQUOTE>	<P><HR><FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Practice safe computing: Initialize	your pointers! <HR></BLOCKQUOTE><P>If you do initialize the pointer to <TT>0</TT>, you must specifically assign theaddress of <TT>howOld</TT> to <TT>pAge</TT>. Here's an example that shows how todo that:</P><PRE><FONT COLOR="#0066FF">unsigned short int howOld = 50;     // make a variableunsigned short int * pAge = 0;      // make a pointerpAge = &amp;howOld;                     // put howOld's address in pAge</FONT></PRE><P>The first line creates a variable--<TT>howOld</TT>, whose type is <TT>unsignedshort int</TT>--and initializes it with the value <TT>50</TT>. The second line declares<TT>pAge</TT> to be a pointer to type <TT>unsigned short int</TT> and initializesit to zero. You know that <TT>pAge</TT> is a pointer because of the asterisk (<TT>*</TT>)after the variable type and before the variable name.</P><P>The third and final line assigns the address of <TT>howOld</TT> to the pointer<TT>pAge</TT>. You can tell that the address of <TT>howOld</TT> is being assignedbecause of the <TT>address of</TT> operator (<TT>&amp;</TT>). If the <TT>addressof</TT> operator had not been used, the value of <TT>howOld</TT> would have beenassigned. That might, or might not, have been a valid address.</P><P>At this point, <TT>pAge</TT> has as its value the address of <TT>howOld</TT>.<TT>howOld</TT>, in turn, has the value <TT>50</TT>. You could have accomplishedthis with one less step, as in</P><PRE><FONT COLOR="#0066FF">unsigned short int howOld = 50;       // make a variableunsigned short int * pAge = &amp;howOld;  // make pointer to howOld</FONT></PRE><P><TT>pAge</TT> is a pointer that now contains the address of the <TT>howOld</TT>variable. Using <TT>pAge</TT>, you can actually determine the value of <TT>howOld</TT>,which in this case is <TT>50</TT>. Accessing <TT>howOld</TT> by using the pointer<TT>pAge</TT> is called indirection because you are indirectly accessing <TT>howOld</TT>by means of<TT> pAge</TT>. Later today you will see how to use indirection to accessa variable's value.</P><DL>	<DD><HR><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>Indirection means accessing	the value at the address held by a pointer. The pointer provides an indirect way	to get the value held at that address. <HR></DL><H4 ALIGN="CENTER"><A NAME="Heading9"></A><FONT COLOR="#000077">Pointer Names</FONT></H4><P>Pointers can have any name that is legal for other variables. This book followsthe convention of naming all pointers with an initial <TT>p</TT>, as in <TT>pAge</TT>or <TT>pNumber</TT>.<H4 ALIGN="CENTER"><A NAME="Heading10"></A><FONT COLOR="#000077">The IndirectionOperator</FONT></H4><P>The indirection operator (<TT>*</TT>) is also called the dereference operator.When a pointer is dereferenced, the value at the address stored by the pointer isretrieved.</P><P>Normal variables provide direct access to their own values. If you create a newvariable of type <TT>unsigned short int</TT> called <TT>yourAge</TT>, and you wantto assign the value in <TT>howOld</TT> to that new variable, you would write</P><PRE><FONT COLOR="#0066FF">unsigned short int yourAge;yourAge = howOld;</FONT></PRE><P>A pointer provides indirect access to the value of the variable whose addressit stores. To assign the value in <TT>howOld</TT> to the new variable <TT>yourAge</TT>by way of the pointer <TT>pAge</TT>, you would write</P><PRE><FONT COLOR="#0066FF">unsigned short int yourAge;

⌨️ 快捷键说明

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