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

📄 apf.htm

📁 Learning language of Visual C++6
💻 HTM
📖 第 1 页 / 共 5 页
字号:
	26, "Exceptions and Templates." Many developers find the MFC map classes
	much easier to use than templates. There are also MFC collection templates, discussed
	later in this chapter. 
<HR>


</BLOCKQUOTE>

<H3><A NAME="Heading15"></A>Introducing the Map Application</H3>
<P>This section's sample program, Map, displays the contents of a map and enables
you to retrieve values from the map by giving the program the appropriate key. When
you run the program, you see the window shown in Figure F.12.</P>
<P>The window displays the contents of the application's map object, in which digits
are used as keys to access the words that represent the numbers. To retrieve a value
from the map, click in the window. You then see the dialog box shown in Figure F.13.
Type the digit that you want to use for a key and click OK. The program finds the
matching value in the map and displays it in another message box. For example, if
you type <B>8</B> as the key, you see the message box shown in Figure F.14. If the
key doesn't exist, the program's message box tells you so.</P>
<P><A HREF="javascript:popUp('xfuvc12.gif')"><B>FIG. F.12</B></A><B> </B><I>The Map
application displays the contents of a map object.</I></P>
<P><A HREF="javascript:popUp('xfuvc13.gif')"><B>FIG. F.13</B></A><B> </B><I>The Get
Map Value dialog box enables you to match a key with the key's value in the map.</I></P>
<P><A HREF="javascript:popUp('xfuvc14.gif')"><B>FIG. F.14</B></A><B> </B><I>This
message box displays the requested map value.</I></P>
<P>
<H3><A NAME="Heading16"></A>Creating and Initializing the Map</H3>
<P>The Map application begins with a 10-element map. The map object is declared as
a data member of the view class, like this:</P>
<P>
<PRE>CMapStringToString map;
</PRE>
<P>This is an object of the CMapStringToString class, which means that the map uses
strings as keys and strings as values.</P>
<P>Declaring the map object doesn't, of course, fill it with values. You have to
do that on your own, which the Map application does in its view class constructor,
shown in Listing F.10.</P>
<P>
<H4>Listing F.10&#160;&#160;CMapView Constructor</H4>
<PRE>CMapView::CMapView()
{
     map.SetAt(&quot;1&quot;, &quot;One&quot;);
     map.SetAt(&quot;2&quot;, &quot;Two&quot;);
     map.SetAt(&quot;3&quot;, &quot;Three&quot;);
     map.SetAt(&quot;4&quot;, &quot;Four&quot;);
     map.SetAt(&quot;5&quot;, &quot;Five&quot;);
     map.SetAt(&quot;6&quot;, &quot;Six&quot;);
     map.SetAt(&quot;7&quot;, &quot;Seven&quot;);
     map.SetAt(&quot;8&quot;, &quot;Eight&quot;);
     map.SetAt(&quot;9&quot;, &quot;Nine&quot;);
     map.SetAt(&quot;10&quot;, &quot;Ten&quot;);
</PRE>
<PRE>}
</PRE>
<P>The SetAt() function takes as parameters the key and the value to associate with
the key in the map. If the key already exists, the function replaces the value associated
with the key with the new value given as the second argument.</P>
<P>
<H3><A NAME="Heading17"></A>Retrieving a Value from the Map</H3>
<P>When you click in Map's window, the Get Map Value dialog box appears, so it's
probably not surprising that the view class OnLButtonDown() member function comes
into play somewhere. Listing F.11 shows this function.</P>
<P>
<H4>Listing F.11&#160;&#160;CMapView::OnLButtonDown()</H4>
<PRE>void CMapView::OnLButtonDown(UINT nFlags, CPoint point) 
{
// Initialize the dialog box.    
    GetMapDlg dialog(this);
    dialog.m_key = &quot;&quot;;
    // Display the dialog box.
    int result = dialog.DoModal();
    // If the user exits with the OK button...
    if (result == IDOK)
    {
        // Look for the requested value.
        CString value;
        BOOL found = map.Lookup(dialog.m_key, value);
        if (found)
            MessageBox(value);
        else
            MessageBox(&quot;No matching value.&quot;);
    }
    CView::OnLButtonDown(nFlags, point);
</PRE>
<PRE>}
</PRE>
<P>In OnLButtonDown(), the program displays the dialog box in the usual way, checking
whether the user exited the dialog box by clicking the OK button. If the user did,
the program calls the map object's Lookup() member function, using the key that the
user entered in the dialog box as the first argument. The second argument is a reference
to the string in which the function can store the value it retrieves from the map.
If the key can't be found, the Lookup() function returns FALSE; otherwise, it returns
TRUE. The program uses this return value to determine whether it should display the
string value retrieved from the map or a message box indicating an error.</P>
<P>
<H3><A NAME="Heading18"></A>Iterating Over the Map</H3>
<P>To display the keys and values used in the map, the program must iterate over
the map, moving from one entry to the next, retrieving and displaying the information
for each map element. As with the array and list examples, the Map application accomplishes
this in its OnDraw() function, which is shown in Listing F.12.</P>
<P>
<H4>Listing F.12&#160;&#160;CMapView::OnDraw()</H4>
<PRE>void CMapView::OnDraw(CDC* pDC)
{
    CMapDoc* pDoc = GetDocument();
    ASSERT_VALID(pDoc);
    TEXTMETRIC textMetric;
    pDC-&gt;GetTextMetrics(&amp;textMetric);
    int fontHeight = textMetric.tmHeight;
    int displayPosition = 10;
    POSITION pos = map.GetStartPosition();
    CString key;
    CString value;
    while (pos != NULL)
    {
        map.GetNextAssoc(pos, key, value);
        CString str = &quot;Key `&quot; + key + 
            &quot;` is associated with the value `&quot; +
            value + &quot;`&quot;;
        pDC-&gt;TextOut(10, displayPosition, str);
        displayPosition += fontHeight;
    }
</PRE>
<PRE>}
</PRE>
<P>Much of this OnDraw() function is similar to other versions that you've seen in
this chapter. The map iteration, however, begins when the program calls the map object's
GetStartPosition() member function, which returns a position value for the first
entry in the map (not necessarily the first entry that you added to the map). Inside
a while loop, the program calls the map object's GetNextAssoc() member function,
giving the position returned from GetStartPosition() as the single argument. GetNextAssoc()
retrieves the key and value at the given position and then updates the position to
the next element in the map. When the position value becomes NULL, the program has
reached the end of the map.</P>
<P>
<H2><A NAME="Heading19"></A>Collection Class Templates</H2>
<P>MFC includes class templates that you can use to create your own special types
of collection classes. (For more information on templates, please refer to the section
&quot;Exploring Templates&quot; in Chapter 26.) Although the subject of templates
can be complex, using the collection class templates is easy enough. For example,
suppose that you want to create an array class that can hold structures of the type
shown in Listing F.13.</P>
<P>
<H4>Listing F.13&#160;&#160;A Sample Structure</H4>
<PRE>struct MyValues
{
    int value1;
    int value2;
    int value3;
</PRE>
<PRE>};
</PRE>
<P>The first step is to use the template to create your class, like this:</P>
<P>
<PRE>CArray&lt;MyValues, MyValues&amp;&gt; myValueArray;
</PRE>
<P>Here, CArray is the template you use for creating your own array classes. The
template's two arguments are the type of data to store in the array and the type
of data that the new array class's member functions should use as arguments where
appropriate. In this case, the type of data to store in the array is structures of
the MyValues type. The second argument specifies that class member functions should
expect references to MyValues structures as arguments, where needed.</P>
<P>To build your array, you optionally set the array's initial size:</P>
<P>
<PRE>myValueArray.SetSize(10, 5);
</PRE>
<P>Then you can start adding elements to the array, like this:</P>
<P>
<PRE>MyValues myValues;
myValueArray.Add(myValues);
</PRE>
<P>After you create your array class from the template, you use the array as you
do any of MFC's array classes, described earlier in this chapter. Other collection
class templates you can use are CList and CMap. This means you can take advantage
of all the design work put in by the MFC team to create an array of Employee objects,
or a linked list of Order objects, or a map linking names to Customer objects.</P>
<P>
<H2><A NAME="Heading20"></A>The String Class</H2>
<P>There are few programs that don't have to deal with text strings of one sort or
another. Unfortunately, C++ is infamous for its weak string-handling capabilities,
whereas languages such as BASIC and Pascal have always enjoyed superior power when
it comes to these ubiquitous data types. MFC's CString class addresses C++'s string
problems by providing member functions that are as handy to use as those found in
other languages. Table F.4 lists the commonly used member functions of the CString
class.</P>
<P>
<H4>Table F.4&#160;&#160;Commonly Used Member Functions of the CString Class</H4>
<P>
<TABLE BORDER="1">
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT"><B>Function</B></TD>
		<TD ALIGN="LEFT"><B>Description</B></TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Compare()</TD>
		<TD ALIGN="LEFT">A case-sensitive compare of two strings</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">CompareNoCase()</TD>
		<TD ALIGN="LEFT">Not a case-sensitive compare of two strings</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Empty()</TD>
		<TD ALIGN="LEFT">Clears a string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Find()</TD>
		<TD ALIGN="LEFT">Locates a substring</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Format()</TD>
		<TD ALIGN="LEFT">&quot;Prints&quot; variables in a CString much like the C sprintf function</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">GetAt()</TD>
		<TD ALIGN="LEFT">Gets a character at a specified position in the string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">GetBuffer()</TD>
		<TD ALIGN="LEFT">Gets a pointer to the string's contents</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">GetLength()</TD>
		<TD ALIGN="LEFT">Gets the number of characters in the string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">IsEmpty()</TD>
		<TD ALIGN="LEFT">Returns TRUE if the string holds no characters</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Left()</TD>
		<TD ALIGN="LEFT">Gets a string's left segment</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">MakeLower()</TD>
		<TD ALIGN="LEFT">Lowercases a string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">MakeReverse()</TD>
		<TD ALIGN="LEFT">Reverses a string's contents</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">MakeUpper()</TD>
		<TD ALIGN="LEFT">Uppercases a string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Mid()</TD>
		<TD ALIGN="LEFT">Gets a string's middle segment</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">Right()</TD>
		<TD ALIGN="LEFT">Gets a string's right segment</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">SetAt()</TD>
		<TD ALIGN="LEFT">Sets a character at a specified position in the string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">TrimLeft()</TD>
		<TD ALIGN="LEFT">Removes leading whitespace characters from a string</TD>
	</TR>
	<TR ALIGN="LEFT" VALIGN="TOP">
		<TD ALIGN="LEFT">TrimRight()</TD>
		<TD ALIGN="LEFT">Removes trailing whitespace characters from a string</TD>
	</TR>
</TABLE>
</P>
<P>Besides the functions listed in the table, the CString class also defines a full
set of operators for dealing with strings. Using these operators, you can do things
like <I>concatenate</I> (join together) strings with the plus sign (+), assign values
to a string object with the equal sign (=), access the string as a C-style string
with the LPCTSTR operator, and more.</P>
<P>Creating a string object is quick and easy, like this:</P>
<P>
<PRE>CString str = &quot;This is a test string&quot;;
</PRE>
<P>Of course, there are lots of ways to construct your string object. The previous
example is only one possibility. You can create an empty string object and assign
characters to it later, you can create a string object from an existing string object,
and you can even create a string from a repeating character. The one thing you don't
have to do is decide the size of your string as you make it. Managing the memory
isn't your problem any more.</P>
<P>After you have created the string object, you can call its member functions and
manipulate the string in a number of ways. For example, to convert all the characters
in the string to uppercase, you'd make a function call like this:</P>
<P>
<PRE>str.MakeUpper();
</PRE>
<P>To lengthen a string, use the + or += operators, like this:</P>
<P>
<PRE>CString sentence = &quot;hello &quot; + str;
sentence += &quot; there.&quot;
</PRE>
<P>To compare two strings, you'd make a function call like this:</P>
<P>
<PRE>str.Compare(&quot;Test String&quot;);
</PRE>
<P>You can also compare two CString objects:</P>
<P>
<PRE>CString testStr = &quot;Test String&quot;;
str.Compare(testStr);
</PRE>

⌨️ 快捷键说明

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