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

📄 apa.htm

📁 Learning language of Visual C++6
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>

<HEAD>
<SCRIPT LANGUAGE="JavaScript">

<!--

function popUp(pPage) {
 var fullURL = document.location;
 var textURL = fullURL.toString();
 var URLlen = textURL.length;
 var lenMinusPage = textURL.lastIndexOf("/");
 lenMinusPage += 1;
 var fullPath = textURL.substring(0,lenMinusPage);
 popUpWin = window.open('','popWin','resizable=yes,scrollbars=no,width=525,height=394');
 figDoc= popUpWin.document;
 zhtm= '<HTML><HEAD><TITLE>' + pPage + '</TITLE>';
 zhtm += '<link rel="stylesheet" href="/includes/stylesheets/ebooks.css"></head>';
 zhtm += '<BODY bgcolor="#FFFFFF">';
 zhtm += '<IMG SRC="' + fullPath + pPage + '">';
 zhtm += '<P><B>' + pPage + '</B>';
 zhtm += '</BODY></HTML>';
 window.popUpWin.document.write(zhtm);
 window.popUpWin.document.close();
 // Johnny Jackson 4/28/98
 }

//-->
                                                                
</SCRIPT>
<link rel="stylesheet" href="/includes/stylesheets/ebooks.css">

	
	<TITLE>Special Edition Using Visual C++ 6 -- Appendix A -- C++ Review and Object-Oriented Concepts</TITLE>
</HEAD>

<BODY TEXT="#000000" BGCOLOR="#FFFFFF">

<CENTER>
<H1><IMG SRC="../button/que.gif" WIDTH="171" HEIGHT="66" ALIGN="BOTTOM" BORDER="0"><BR>
Special Edition Using Visual C++ 6</H1>
</CENTER>
<CENTER>
<P><A HREF="../ch28/ch28.htm"><IMG SRC="../button/previous.gif" WIDTH="128" HEIGHT="28"
ALIGN="BOTTOM" ALT="Previous chapter" BORDER="0"></A><A HREF="../apb/apb.htm"><IMG
SRC="../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>- A -</H1>
</CENTER>
<CENTER>
<H1>C++ Review and Object-Oriented Concepts</H1>
</CENTER>

<UL>
	<LI><A HREF="#Heading1">Working with Objects</A>
	<UL>
		<LI><A HREF="#Heading2">What Is an Object?</A>
		<LI><A HREF="#Heading3">Why Use Objects?</A>
		<LI><A HREF="#Heading4">What Is a Class?</A>
		<LI><A HREF="#Heading5">Where Are the Functions?</A>
		<LI><A HREF="#Heading6">How Are Objects Initialized?</A>
		<LI><A HREF="#Heading7">What Is Overloading?</A>
	</UL>
	<LI><A HREF="#Heading8">Reusing Code and Design with Inheritance</A>
	<UL>
		<LI><A HREF="#Heading9">What Is Inheritance?</A>
		<LI><A HREF="#Heading10">What Is Protected Access?</A>
		<LI><A HREF="#Heading11">What Is Overriding?</A>
		<LI><A HREF="#Heading12">What Is Polymorphism?</A>
	</UL>
	<LI><A HREF="#Heading13">Managing Memory</A>
	<UL>
		<LI><A HREF="#Heading14">Allocating and Releasing Memory</A>
		<LI><A HREF="#Heading15">Pointers as Member Variables</A>
		<LI><A HREF="#Heading16">Dynamic Objects</A>
		<LI><A HREF="#Heading17">Destructors and Pointers</A>
		<LI><A HREF="#Heading18">Running Destructors Accidentally</A>
		<LI><A HREF="#Heading19">What Else Should I Know?</A>
	</UL>
</UL>

<P>
<HR SIZE="4">

<CENTER>
<H1></H1>
</CENTER>
<H2><A NAME="Heading1"></A>Working with Objects</H2>
<P>C++ is an object-oriented programming language. You can use it to write programs
that are not object-oriented, like the &quot;Hello World!&quot; example in Chapter
28, &quot;Future Explorations,&quot; but its real power comes from the way it helps
you to implement your applications as objects rather than procedures. As a Visual
C++ programmer, you will make extensive use of MFC, the Microsoft Foundation Classes:
These are implementations of objects almost every application uses.</P>


<BLOCKQUOTE>
	<P>
<HR>
<STRONG>TIP:</STRONG> If you never worked with C++ before you picked up this book,
	you are likely to need more help than one chapter can provide. As an introduction,
	consider using any of Jesse Liberty's books on C++: <I>Sams Teach Yourself C++ in
	24 Hours</I>,<I> Sams Teach Yourself C++ in 21 Days</I>, or <I>Sams Teach Yourself
	C++ in 21 Days: Complete Compiler Edition</I>. 
<HR>


</BLOCKQUOTE>

<H3><A NAME="Heading2"></A>What Is an Object?</H3>
<P>An object is a bundle, a clump, a gathering together of items of information that
belong together, and functions that work on those items of information. For example,
a BankAccount object might gather up a customer number, account number, and current
balance--these three pieces of information are required for all bank accounts. Many
languages provide a way to group related information together into <I>structures</I>
or <I>records</I> or whatever the language calls the feature. However, where an object
differs from these is in including functions, or behavior, as well as information.
Our BankAccount object will have Deposit(), Withdraw(), and GetBalance() functions,
for example. Figure A.1 shows one way of looking at the design of an object.</P>
<P><A HREF="javascript:popUp('appafig01.gif')"><B>FIG. A.1</B></A><B> </B><I>Objects
combine information (variables) and behavior (functions).</I></P>
<P>
<H3><A NAME="Heading3"></A>Why Use Objects?</H3>
<P>There are many advantages to an object-oriented approach to application development,
but the two most important are maintanability and robustness. That's what you call
them when you're persuading your manager to switch to C++. In your day-to-day life,
they mean you can change one thing without breaking anything else, and you don't
have to count on remembering to always do step B whenever you do step A. Both these
benefits arise because code from outside our BankAccount object can't directly access
any information inside the object, only through the functions you've added to the
object. For example, imagine that some piece of code creates a bank account like
this:</P>
<P>
<PRE>BankAccount account;
</PRE>
<P>That code can now deposit or withdraw money or find out the balance in the account,
like this:</P>
<P>
<PRE>account.Deposit(100.00);
account.Withdraw(50.00);
float newbalance = account.GetBalance();
</PRE>
<P>That code cannot work on the balance directly, like this:</P>
<P>
<PRE>account.balance = 100.00;
account.balance -= 50.00;
float newbalance = account.balance;
</PRE>
<P>This information hiding doesn't seek to protect the numeric value of the account
balance--the three lines of code that work are obviously using and affecting that
value. Instead, information hiding protects design decisions made by the programmer,
and it leaves you free to change them later.</P>
<P>As an example, say you decide to use a floating point number to represent the
account balance, the number of dollars in the account. Later, you change your mind,
deciding that using an integer that represents the number of pennies in the account
would be faster, or more accurate, or less of a burden on available memory. Of course,
you will have to change the code for Deposit() and Withdraw(), which will still take
floating point arguments, to convert from dollars to pennies. After you do that,
all the code that other people wrote that called those functions will work perfectly:
They'll never know you changed anything. If you're the one writing the whole project,
you'll know that you have no work to do other than the changes within your BankAccount
object. If other code could talk to balance directly, as in the second set of three
lines, you'd have to find every place in the whole application that does so and change
it to convert from dollars to pennies or from pennies to dollars. What a nightmare!</P>
<P>What if you never make such a fundamental change as that? After all, it's rare
to change the type of a variable partway through the project. Well then, imagine
a change in the business rules governing withdrawals. When the project started, you
were told that accounts couldn't be overdrawn, so you wrote code for the Withdraw()
function that looked like this:</P>
<P>
<PRE>balance -= amounttowithdraw;
if (balance &lt; 0)
    balance += amounttowithdraw; //reverse transaction
</PRE>
<P>Then, just as the application was almost complete, you were told that, in fact,
many accounts have overdraft protection and you should have written the following:</P>
<P>
<PRE>balance -= amounttowithdraw;
if (balance &lt; -overdraftlimit)
    balance += amounttowithdraw; //reverse transaction
</PRE>
<P>If all withdrawals go through the Withdraw() function, your life is easy: Make
one change in the function, and everything's taken care of. If lots of other places
in the code were processing withdrawals themselves, by just lowering the value of
balance, you would have to find all those places and fix the overdraft check in each
place. If you missed one, your program would have a strange and subtle bug that missed
overdrafts in some situations and caught them in others. The object-oriented way
is much safer.</P>
<P>
<H3><A NAME="Heading4"></A>What Is a Class?</H3>
<P>In any bank, there are many bank accounts: yours, mine, and thousands of others.
They all have fundamental things in common: They have a balance and a customer, and
certain kinds of transactions are allowed with them. In a banking application, you
will have perhaps thousands of bank account objects, and each will be an instance
of the BankAccount class.</P>
<P>When you define a class, you define what it means to be a BankAccount (or a Truck,
or an Employee, or whatever). You list the information that is kept by objects of
this class in the form of member variables, and the things objects of this class
can do, in the form of member functions. Also, you make it clear which parts of the
class you want to protect with information hiding. Listing A.1 shows a declaration
for the class BankAccount.</P>
<P>
<H4>Listing A.1&#160;&#160;Declaring the BankAccount Class</H4>
<PRE>class BankAccount
{
   private:
      float balance;
      char[8] customer_id;
      char[8] account_num;
   public:
    float GetBalance();
    void Withdraw(float amounttowithdraw);
    void Deposit(float amounttodeposit);
</PRE>
<PRE>};
</PRE>
<P>The keyword private before the three variables directs the compiler not to compile
code that accesses these variables, unless that code is within a member function
of BankAccount. The keyword public before the three functions tells the compiler
any code at all can call them. This is a typical arrangement for a well-designed
object-oriented program: All the variables are private, and all the functions are
public.</P>


<BLOCKQUOTE>
	<P>
<HR>
<STRONG>TIP:</STRONG> Occasionally, you might write a function for an object that
	is used to perform some repetitive task. It's not always appropriate for other objects
	to use that function to direct your object to perform that task. In this case, you
	can make the function private. Many developers make variables public to save the
	bother of writing public functions to access the variable. There's rarely a good
	reason to do this; it's just laziness. 
<HR>


</BLOCKQUOTE>

<P>Now if certain code declares two bank accounts, mine and yours, each will have
its own balance, customer_id, and account_num variables. Depositing money into my
bank account will not affect your balance. Listing A.2 shows some code that creates
bank accounts and then exercises their functions.</P>
<P>
<H4>Listing A.2&#160;&#160;Using BankAccount Objects</H4>
<PRE>BankAccount mine, yours;
mine.Deposit(1000);
yours.Deposit(100);
mine.Withdraw(500);
float mybalance = mine.GetBalance();
</PRE>
<PRE>float yourbalance = yours.GetBalance();
</PRE>
<H3><A NAME="Heading5"></A>Where Are the Functions?</H3>
<P>The three member functions--Deposit(), Withdraw(), and GetBalance()--must be written,
and their code must be compiled. You can put the code for these functions in two
places: inside the class declaration (called <I>inline</I> <I>code</I>) or outside
the class declaration, usually in a separate file. Only very short and simple functions
should have inline code because long functions here make the class declaration hard
to read. If all three functions in this sample class had inline code, the class declaration
would be as shown in Listing A.3.</P>
<P>
<H4>Listing A.3&#160;&#160;BankAccount with Inline Code</H4>
<PRE>class BankAccount
{
   private:
      float balance;
      char[8] customer_id;
      char[8] account_num;
   public:
    float GetBalance() { return balance;}
    void Withdraw(float amounttowithdraw)
       {
        balance -= amounttowithdraw;
        if (balance &lt; 0)
           balance += amounttowithdraw; //reverse transaction
       }
    void Deposit(float amounttodeposit) {balance += amounttodeposit;}
</PRE>
<PRE>};
</PRE>
<P>Notice that the semicolon after the function names in Listing A.1 has been replaced
by the function body, surrounded by braces. The Withdraw() function is a little too
long to include in the class declaration like this and would be better placed outside
the class. Because all functions in an object-oriented program belong to a class,
when you provide the code, you must indicate the name of the class to which the function
belongs. Listing A.4 shows the code for Withdraw() as it might appear outside the
class declaration. The two colons (::) between the classname and the function name
are called the <I>scope resolution operator</I>.</P>
<P>
<H4>Listing A.4&#160;&#160;BankAccount's Withdraw() Function</H4>
<PRE>void BankAccount::Withdraw(float amounttowithdraw)
       {
        balance -= amounttowithdraw;
        if (balance &lt; 0)
           balance += amounttowithdraw; //reverse transaction
</PRE>
<PRE>       }
</PRE>


<BLOCKQUOTE>
	<P>
<HR>
<STRONG>NOTE:</STRONG> Usually, the class declaration is placed in a file of its
	own with a name such as BankAccount.h so that it can be used by all the other code
	that makes BankAccount objects or calls BankAccount functions. This file is generally
	referred to as the <I>header</I> <I>file</I>. Typically, the rest of the code is
	placed in another file with a name such as BankAccount.cpp, referred to as the <I>implementation</I>
	<I>file</I>.&#160;n 
<HR>
<BR>
	
<HR>

⌨️ 快捷键说明

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