?? ch03.htm
字號:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"><HTML><HEAD> <TITLE>Teach Yourself Visual C++® 5 in 24 Hours -- Hour 3 -- Structures, Classes, and the MFC Class Library</TITLE></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF"><CENTER><H1><IMG SRC="../button/sams.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"><BR><FONT COLOR="#000077">Teach Yourself Visual C++® 5 in 24 Hours</FONT></H1></CENTER><CENTER><P><A HREF="../ch02/ch02.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../ch04/ch04.htm"><IMGSRC="../button/next.gif" WIDTH="128" HEIGHT="28" ALIGN="BOTTOM" ALT="Next chapter"BORDER="0"></A><A HREF="../index.htm"><IMG SRC="../button/contents.gif" WIDTH="128"HEIGHT="28" ALIGN="BOTTOM" ALT="Contents" BORDER="0"></A> <HR></CENTER><CENTER><H1><FONT COLOR="#000077">- Hour 3 -<BR>Structures, Classes, and the MFC Class Library</FONT></H1></CENTER><P>In the first two hours, you have learned some of the basic concepts behind C++,and you have written some simple programs. In this hour, you will be introduced tosome more advanced Visual C++ programming topics. In particular, you will learn<UL> <LI>How functions are used to provide small reusable chunks of code<BR> <BR> <LI>How structures and classes are used to create source code and data components<BR> <BR> <LI>How expressions and statements are used in C++ programs<BR> <BR> <LI>How to use the MFC class library to write Windows programs without using ClassWizard</UL><P>You will also build sample programs that illustrate the topics you learn aboutin this hour.<H2><FONT COLOR="#000077"><B>Using Functions</B></FONT></H2><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>function</I> is a groupof computer instructions that performs a well-defined task inside a computer program.</P><P>Functions are one of the primary building blocks of C and C++ applications. Functionsprovide a way to break up a large program into more manageable parts. At the sametime, functions make it possible to perform the same task at various points withinthe program without repeating the code.</P><P>For example, If you buy a wagon, you'll find that it comes with a full set ofassembly instructions and has four identical wheels. Why should the instructionsrepeat the steps to assemble a wheel four times? It is much easier to describe thewheel assembly process once and indicate that you perform the process for each wheel.The wheel assembly instructions are a module (function), within the full set of assemblyinstructions (program), that is executed four times.</P><P>Every C++ program has at least one function; this function is called <TT>main</TT>.The <TT>main</TT> function is called by the operating system when your applicationstarts; when <TT>main</TT> has finished executing, your program has finished.<H3><FONT COLOR="#000077"><B>Declaring Function Prototypes</B></FONT></H3><P>Before you can use a function, you must declare it by supplying a function prototypeto the compiler. To declare a function, you specify the function's name, its returnvalue, and a list of any parameters that are passed to it, as shown here:</P><PRE><FONT COLOR="#0066FF"><TT>int CalculateAge(int nYearBorn);</TT></FONT></PRE><P>This line is a function prototype for the <TT>CalculateAge</TT> function, whichtakes a single integer as a parameter and returns an integer as its result. A functionthat returns no value is declared as returning the <TT>void</TT> type.</P><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>The traditional way to providefunction prototypes is to place them in <I>header</I> files, which are usually namedwith an <TT>.h</TT> extension.</P><P>Header files that are part of the C++ standard library do not use the <TT>.h</TT>extension; two examples of standard header files are <TT>iostream</TT> and <TT>math</TT>.These header files contain all the prototypes and other declarations needed for IOstreams and math functions to be compiled correctly.<H3><FONT COLOR="#000077"><B>Defining Functions</B></FONT></H3><P>A function is defined the same way the <TT>main</TT> function is defined. Allfunction definitions follow the same pattern; it's basically the function prototypewith the function's body added to it. The function definition always consists ofthe following:<UL> <LI>The function's return value<BR> <BR> <LI>The function's name<BR> <BR> <LI>The function's parameter list<BR> <BR> <LI>The actual function body, enclosed in curly braces</UL><P>Listing 3.1 shows how to use a function to display the Hello World! message. Torun this project, create a new console-mode project named HelloFunc, using the stepsdescribed for the Hello and Hello2 projects in the first two hours.<H4><FONT COLOR="#000077">TYPE: Listing 3.1. The Hello World! program rewritten touse a function.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include <iostream></TT><TT>using namespace std;</TT><TT>// Function prototype</TT><TT>void DisplayAge(int nAge);</TT><TT>int main()</TT><TT>{</TT><TT> DisplayAge(42);</TT><TT> return 0;</TT><TT>}</TT><TT>void DisplayAge(int nAge)</TT><TT>{</TT><TT> cout << "Hello World! I'm " << nAge << " years old." endl;</TT><TT>}</TT></FONT></PRE><P>Because the function doesn't return a value to the calling function, the returntype is defined as <TT>void</TT>.<H3><FONT COLOR="#000077"><B>Calling Functions</B></FONT></H3><P>In the C++ language, the act of transferring control to a function is known as<I>calling</I> the function. When a function is called, you supply a function nameand a list of parameters, if any. The following steps take place when a functionis called:<DL> <DD>1. The compiler makes a note of the location from which the function was called and makes a copy of the parameter list, if any.<BR> <BR> 2. Any storage required for the function to execute is temporarily created.<BR> <BR> 3. The called function starts executing, using copies of the data that was supplied in the parameter list.<BR> <BR> 4. After the function has finished executing, control is returned to the calling function, and memory used by the function is released.</DL><P>These steps are shown in Figure 3.1, which uses the function from Listing 3.1as an example.</P><P><A NAME="01"></A><A HREF="01.htm"><B>Figure 3.1.</B></A><BR><I>Steps involved in calling a function.</I><BLOCKQUOTE> <P><HR><B> </B><FONT COLOR="#000077"><B>Just a Minute:</B></FONT><B> </B>The requirement that you declare functions before using them is an extension of the C++ type system. Because function prototypes are required, the compiler can detect errors such as incorrect parameters used in a function call. <HR></BLOCKQUOTE><H2><FONT COLOR="#000077"><B>What Are Structures?</B></FONT></H2><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>structure</I> is a datatype that is an aggregate; that is, it contains other data types, which are groupedtogether into a single user-defined type.<BLOCKQUOTE> <P><HR><B> </B><FONT COLOR="#000077"><B>Just a Minute:</B></FONT><B> </B>Structures are commonly used when it makes sense to associate two or more data variables. <HR></BLOCKQUOTE><P>An example of a structure is a payroll record, where the number of hours workedand the pay rate are combined in a structure, as shown in Figure 3.2.</P><P><A NAME="02"></A><A HREF="02.htm"><B>Figure 3.2.</B> </A><I><BR>Structures are made up of member variables.</I></P><P>Declaring a structure introduces a new type of variable into your program. Variablesof this new type can be defined just like <TT>int</TT>, <TT>char,</TT> or <TT>float</TT>variables are defined. Listing 3.2 is an example of how a structure is typicallyused.<H4><FONT COLOR="#000077">TYPE: Listing 3.2. Using a structure to calculate a weeklysalary.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include <iostream.h></TT><TT>struct TIME_REC</TT><TT>{</TT><TT> double dHours;</TT><TT> double dRate;</TT><TT>};</TT><TT>int main()</TT><TT>{</TT><TT> TIME_REC payrollRecord;</TT><TT> payrollRecord.dHours = 40.0;</TT><TT> payrollRecord.dRate = 3.75;</TT><TT> cout << "This week's payroll information:" << endl;</TT><TT> cout << "Hours worked : " << payrollRecord.dHours << endl;</TT><TT> cout << "Rate :$" << payrollRecord.dRate << endl;</TT><TT> double dSalary = payrollRecord.dRate * payrollRecord.dHours;</TT><TT> cout << "Salary :$" << dSalary << endl;</TT><TT> return 0;</TT><TT>}</TT></FONT></PRE><H2><FONT COLOR="#000077"><B>What Are Classes?</B></FONT></H2><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>class</I> allows dataand functions to be bundled together and used as if they are a single element. Classestypically model real-world concepts that have both data and some sort of behavior,although this is not a hard and fast rule.</P><P>Classes are similar to structures; in fact, classes really are just structureswith a different name. Classes have one feature that makes them very useful for object-orientedprogramming: Unless a member of a class is specifically declared as <TT>public</TT>,that member is generally not accessible from outside the class. This means that youcan hide the implementation of methods behind the external interface.<BLOCKQUOTE> <P><HR><B> </B><FONT COLOR="#000077"><B>Just a Minute:</B></FONT><B> </B>Like functions, classes are an important part of the C++ programming language. In fact, one of the earliest names for C++ was C with Classes. <HR></BLOCKQUOTE><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>An <I>instance</I> of a class,sometimes called an <I>object</I>, is an occurrence of a class. An instance of oneof your classes can be used or manipulated inside your programs.</P><P>You normally use classes to model objects in your program. Member functions, describedin the next section, are used to control the state of an object, as well as to accessany data contained in it.</P><P>In programs written with MFC, classes are used to model different parts of theapplication, such as the window frame, menus, buttons, and other controls. Memberfunctions are used to handle specific work that needs to be handled by the class.<H3><FONT COLOR="#000077"><B>Classes Versus Instances</B></FONT></H3><P>Classes and instances of classes are not the same things--this can sometimes bea confusing concept if you are new to C++ or object-oriented programming. Think ofa class as the description of an object; an instance of a class is a concrete occurrenceof that class.<H3><FONT COLOR="#000077"><B>Constructors</B></FONT></H3><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>constructor</I>, sometimescalled a "ctor," is a special member function that is created when an objectof the class is created.</P><P>A constructor always has the same name as the class and never has a return value,not even <TT>void</TT>. The purpose of the constructor is to place a newly createdobject into a known state. Typically, constructors can allocate system resources,clear or set variables, or perform some other type of initialization.<H3><FONT COLOR="#000077"><B>Destructors</B></FONT></H3><P><FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>destructor</I>, sometimescalled a "dtor," is a special member function that is called as an objectis destroyed. The destructor is declared as having no return type and is never declaredwith a parameter list. The name of the destructor is the class name prefixed by atilde (~) character.</P><P>It is not necessary to define a destructor unless there are specific tasks thatmust be performed to clean up after an object, such as releasing system resourcesthat might have been allocated.<H2><FONT COLOR="#000077"><B>Using MFC for Windows Programming</B></FONT></H2><P>In the first hour, you created an MFC program using AppWizard. When you use AppWizardto create a project, it might seem that you get a great deal of functionality forfree. However, a great deal of code is generated--even a simple program like HelloMFCresults in a large number of source files.</P><P>MFC doesn't need to be that complicated. In fact, you can write a very simpleMFC program that fits in a single source file and is about one page long.<H3><FONT COLOR="#000077"><B>The HelloWin MFC Example</B></FONT></H3><P>Listing 3.3 is an example of a simple MFC program that displays a Hello Worldmessage in the center of the client window, much like the HelloMFC program you createdin the first hour.<H4><FONT COLOR="#000077">TYPE: Listing 3.3. A simple Windows program written usingC++ and MFC.</FONT></H4><PRE><FONT COLOR="#0066FF"><TT>#include <afxwin.h></TT><TT>// The CHelloApp class</TT><TT>class CHelloApp : public CWinApp</TT><TT>{</TT><TT> public:</TT><TT> BOOL InitInstance();</TT><TT>};</TT><TT>// The CHelloWnd class</TT><TT>class CHelloWnd : public CFrameWnd</TT><TT>{</TT><TT> public:</TT><TT> CHelloWnd();</TT><TT> protected:</TT><TT> afx_msg void OnPaint();</TT><TT> DECLARE_MESSAGE_MAP()</TT><TT>};</TT><TT>// InitInstance - Returns TRUE if initialization is successful.</TT><TT>BOOL CHelloApp::InitInstance()</TT><TT>{</TT><TT> m_pMainWnd = new CHelloWnd;</TT><TT> if( m_pMainWnd != 0 )</TT><TT> {</TT><TT> m_pMainWnd->ShowWindow( m_nCmdShow );</TT><TT> m_pMainWnd->UpdateWindow();</TT><TT> return TRUE;</TT><TT> }</TT><TT> else</TT><TT> return FALSE;</TT><TT>}</TT><TT>// Create a message map that handles one message - WM_PAINT</TT><TT>BEGIN_MESSAGE_MAP( CHelloWnd, CFrameWnd )</TT><TT> ON_WM_PAINT()</TT><TT>END_MESSAGE_MAP()</TT><TT>CHelloWnd::CHelloWnd()</TT><TT>{</TT><TT> Create( NULL, "Hello" );</TT><TT>}</TT><TT>// OnPaint - Handles the WM_PAINT message from Windows.</TT><TT>void CHelloWnd::OnPaint()</TT><TT>{</TT><TT> CPaintDC dc(this);</TT><TT> dc.TextOut(50, 50, "Hello World!", 12);</TT><TT>}</TT><TT>// Create a single instance of the application.</TT><TT>CHelloApp theApplication; </TT></FONT></PRE>
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -