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

📄 ch06.htm

📁 good book for learning c++ standard language
💻 HTM
📖 第 1 页 / 共 5 页
字号:
</FONT></PRE>
<P>In the same way, to call the <TT>Meow()</TT> function, you would write</P>
<PRE><FONT COLOR="#0066FF">Frisky.Meow();
</FONT></PRE>
<P>When you use a class method, you call the method. In this example, you are calling
<TT>Meow()</TT> on Frisky.
<H4 ALIGN="CENTER"><A NAME="Heading11"></A><FONT COLOR="#000077">Assign to Objects,
Not to Classes</FONT></H4>
<P>In C++ you don't assign values to types; you assign values to variables. For example,
you would never write</P>
<PRE><FONT COLOR="#0066FF">int = 5;               // wrong
</FONT></PRE>
<P>The compiler would flag this as an error, because you can't assign <TT>5</TT>
to an integer. Rather, you must define an integer variable and assign <TT>5</TT>
to that variable. For example,</P>
<PRE><FONT COLOR="#0066FF">int  x;                // define x to be an int
x = 5;                 // set x's value to 5
</FONT></PRE>
<P>This is a shorthand way of saying, &quot;Assign <TT>5</TT> to the variable <TT>x</TT>,
which is of type <TT>int</TT>.&quot; In the same way, you wouldn't write</P>
<PRE><FONT COLOR="#0066FF">Cat.age=5;             // wrong
???
</FONT></PRE>
<P>The compiler would flag this as an error, because you can't assign <TT>5</TT>
to the age part of a <TT>Cat</TT>. Rather, you must define a <TT>Cat</TT> object
and assign <TT>5</TT> to that object. For example,</P>
<PRE><FONT COLOR="#0066FF">Cat Frisky;            // just like  int x;
Frisky.age = 5;        // just like  x = 5;
</FONT></PRE>
<H4 ALIGN="CENTER"><A NAME="Heading12"></A><FONT COLOR="#000077">If You Dont Declare
It, Your Class Wont Have It</FONT></H4>
<P>Try this experiment: Walk up to a three-year-old and show her a cat. Then say,
&quot;This is Frisky. Frisky knows a trick. Frisky, bark.&quot; The child will giggle
and say, &quot;No, silly, cats can't bark.&quot;</P>
<P>If you wrote</P>
<PRE><FONT COLOR="#0066FF">Cat  Frisky;           // make a Cat named Frisky
Frisky.Bark()          // tell Frisky to bark
</FONT></PRE>
<P>the compiler would say, <TT>No, silly, Cats can't bark</TT>. (Your compiler's
wording may vary). The compiler knows that Frisky can't bark because the <TT>Cat</TT>
class doesn't have a <TT>Bark()</TT> function. The compiler wouldn't even let Frisky
meow if you didn't define a <TT>Meow()</TT> function.


<BLOCKQUOTE>
	<P>
<HR>
<B>DO </B>use the keyword <TT>class</TT> to declare a class. <B>DON'T</B> confuse
	a declaration with a definition. A declaration says what a class is. A definition
	sets aside memory for an object. <B>DON'T</B> confuse a class with an object. <B>DON'T</B>
	assign values to a class. Assign values to the data members of an object. <B>DO</B>
	use the dot operator (<TT>.</TT>) to access class members and functions. 
<HR>


</BLOCKQUOTE>

<H3 ALIGN="CENTER"><A NAME="Heading13"></A><FONT COLOR="#000077">Private Versus Public</FONT></H3>
<P>Other keywords are used in the declaration of a class. Two of the most important
are <TT>public</TT> and <TT>private</TT>.</P>
<P>All members of a class--data and methods--are private by default. Private members
can be accessed only within methods of the class itself. Public members can be accessed
through any object of the class. This distinction is both important and confusing.
To make it a bit clearer, consider an example from earlier in this chapter:</P>
<PRE><FONT COLOR="#0066FF">class Cat
{
unsigned int  itsAge;
unsigned int  itsWeight;
Meow();
};
</FONT></PRE>
<P>In this declaration, <TT>itsAge</TT>, <TT>itsWeight</TT>, and <TT>Meow()</TT>
are all private, because all members of a class are private by default. This means
that unless you specify otherwise, they are private.</P>
<P>However, if you write</P>
<PRE><FONT COLOR="#0066FF">Cat  Boots;
Boots.itsAge=5;        // error! can't access private data!
</FONT></PRE>
<P>the compiler flags this as an error. In effect, you've said to the compiler, &quot;I'll
access <TT>itsAge</TT>, <TT>itsWeight</TT>, and <TT>Meow()</TT> only from within
member functions of the <TT>Cat</TT> class.&quot; Yet here you've accessed the <TT>itsAge</TT>
member variable of the <TT>Boots</TT> object from outside a <TT>Cat</TT> method.
Just because <TT>Boots</TT> is an object of class <TT>Cat</TT>, that doesn't mean
that you can access the parts of <TT>Boots</TT> that are private.</P>
<P>This is a source of endless confusion to new C++ programmers. I can almost hear
you yelling, &quot;Hey! I just said Boots is a cat. Why can't Boots access his own
age?&quot; The answer is that Boots can, but you can't. Boots, in his own methods,
can access all his parts--public and private. Even though you've created a <TT>Cat</TT>,
that doesn't mean that you can see or change the parts of it that are private.</P>
<P>The way to use <TT>Cat</TT> so that you can access the data members is</P>
<PRE><FONT COLOR="#0066FF">class Cat
{
public:
unsigned int  itsAge;
unsigned int  itsWeight;
Meow();
};
<B></B></FONT></PRE>
<P>Now <TT>itsAge</TT>, <TT>itsWeight</TT>, and <TT>Meow()</TT> are all public. <TT>Boots.itsAge=5</TT>
compiles without problems.<B></B></P>

<P>Listing 6.1 shows the declaration of a <TT>Cat</TT> class with public member variables.</P>

<P><A NAME="Heading14"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.1. Accessing
the public members of a simple class.</B></FONT><FONT COLOR="#0066FF"></FONT></P>
<PRE><FONT COLOR="#0066FF">1:   // Demonstrates declaration of a class and
2:   // definition of an object of the class,
3:
4:   #include &lt;iostream.h&gt;   // for cout
5:
6:   class Cat                // declare the class object
7:   {
8:    public:                 // members which follow are public
9:      int itsAge;
10:     int itsWeight;
11:  };
12:
13:
14:  void main()
15:  {
16:     Cat Frisky;
17:     Frisky.itsAge = 5;    // assign to the member variable
18:     cout &lt;&lt; &quot;Frisky is a cat who is &quot; ;
19:     cout &lt;&lt; Frisky.itsAge &lt;&lt; &quot; years old.\n&quot;;
<TT>20: </TT>
Output: Frisky is a cat who is 5 years old.
</FONT></PRE>
<P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Line 6 contains the keyword
<TT>class</TT>. This tells the compiler that what follows is a declaration. The name
of the new class comes after the keyword <TT>class</TT>. In this case, it is <TT>Cat</TT>.<BR>
The body of the declaration begins with the opening brace in line 7 and ends with
a closing brace and a semicolon in line 11. Line 8 contains the keyword <TT>public</TT>,
which indicates that everything that follows is public until the keyword <TT>private</TT>
or the end of the class declaration.</P>
<P>Lines 9 and 10 contain the declarations of the class members <TT>itsAge</TT> and
<TT>itsWeight</TT>.</P>
<P>Line 14 begins the main function of the program. <TT>Frisky</TT> is defined in
line 16 as an instance of a <TT>Cat</TT>--that is, as a <TT>Cat</TT> object. <TT>Frisky</TT>'s
age is set in line 17 to <TT>5</TT>. In lines 18 and 19, the <TT>itsAge</TT> member
variable is used to print out a message about <TT>Frisky</TT>.


<BLOCKQUOTE>
	<P>
<HR>
<FONT COLOR="#000077"><B>NOTE:</B></FONT><B> </B>Try commenting out line 8 and try
	to recompile. You will receive an error on line 17 because <TT>itsAge</TT> will no
	longer have public access. The default for classes is private access. 
<HR>


</BLOCKQUOTE>

<H4 ALIGN="CENTER"><A NAME="Heading16"></A><FONT COLOR="#000077">Make Member Data
Private</FONT></H4>
<P>As a general rule of design, you should keep the member data of a class private.
Therefore, you must create public functions known as accessor methods to set and
get the private member variables. These accessor methods are the member functions
that other parts of your program call to get and set your private member variables.</P>

<DL>
	<DD>
<HR>
<FONT COLOR="#000077"><B>New Term:</B></FONT><B> </B>A <I>public accessor method</I>
	is a class member function used either to read the value of a private class member
	variable or to set its value. 
<HR>

</DL>

<P>Why bother with this extra level of indirect access? After all, it is simpler
and easier to use the data, instead of working through accessor functions.</P>
<P>Accessor functions enable you to separate the details of how the data is stored
from how it is used. This enables you to change how the data is stored without having
to rewrite functions that use the data.</P>
<P>If a function that needs to know a <TT>Cat</TT>'s age accesses <TT>itsAge</TT>
directly, that function would need to be rewritten if you, as the author of the <TT>Cat</TT>
class, decided to change how that data is stored. By having the function call <TT>GetAge()</TT>,
your <TT>Cat</TT> class can easily return the right value no matter how you arrive
at the age. The calling function doesn't need to know whether you are storing it
as an unsigned integer or a <TT>long</TT>, or whether you are computing it as needed.</P>
<P>This technique makes your program easier to maintain. It gives your code a longer
life because design changes don't make your program obsolete.</P>
<P>Listing 6.2 shows the <TT>Cat</TT> class modified to include private member data
and public accessor methods. Note that this is not an executable listing.</P>

<P><A NAME="Heading17"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.2. A class
with accessor methods.</B></FONT><FONT COLOR="#0066FF"></FONT>
<PRE><FONT COLOR="#0066FF">1:       // Cat class declaration
2:       // Data members are private, public accessor methods
3:       // mediate setting and getting the values of the private data
4:
5:  class Cat
6:  {
7:  public:
8:       // public accessors
9:     unsigned int GetAge();
10:    void SetAge(unsigned int Age);
11:
12:    unsigned int GetWeight();
13:    void SetWeight(unsigned int Weight);
14:
15:      // public member functions
16:    Meow();
17:
18:      // private member data
19: private:
20:    unsigned int  itsAge;
21:    unsigned int  itsWeight;
22:
<TT>23: };</TT></FONT> 
</PRE>
<P><FONT COLOR="#000077"><B>Analysis: </B></FONT>This class has five public methods.
Lines 9 and 10 contain the accessor methods for <TT>itsAge</TT>. Lines 12 and 13
contain the accessor methods for <TT>itsWeight</TT>. These accessor functions set
the member variables and return their values.<BR>
The public member function <TT>Meow()</TT> is declared in line 16. <TT>Meow()</TT>
is not an accessor function. It doesn't get or set a member variable; it performs
another service for the class, printing the word <TT>Meow</TT>.</P>
<P>The member variables themselves are declared in lines 20 and 21. <BR>
<BR>
To set Frisky's age, you would pass the value to the <TT>SetAge()</TT> method, as
in</P>
<PRE><FONT COLOR="#0066FF">Cat  Frisky;
Frisky.SetAge(5);    // set Frisky's age using the public accessor
</FONT></PRE>
<H4 ALIGN="CENTER"><A NAME="Heading19"></A><FONT COLOR="#000077">Privacy Versus Security</FONT></H4>
<P>Declaring methods or data private enables the compiler to find programming mistakes
before they become bugs. Any programmer worth his consulting fees can find a way
around privacy if he wants to. Stroustrup, the inventor of C++, said, &quot;The C++
access control mechanisms provide protection against accident--not against fraud.&quot;
(ARM, 1990.)
<H3 ALIGN="CENTER"><A NAME="Heading20"></A><FONT COLOR="#000077">The class keyword</FONT></H3>
<P>Syntax for the <TT>class</TT> keyword is as follows.</P>
<PRE><FONT COLOR="#0066FF">
class class_name
{
// access control keywords here
// class variables and methods declared here
};
</FONT></PRE>
<P>You use the <TT>class</TT> keyword to declare new types. A class is a collection
of class member data, which are variables of various types, including other classes.
The class also contains class functions--or methods--which are functions used to
manipulate the data in the class and to perform other services for the class. You
define objects of the new type in much the same way in which you define any variable.
State the type (class) and then the variable name (the object). You access the class
members and functions by using the dot (<TT>.</TT>) operator. You use access control
keywords to declare sections of the class as public or private. The default for access
control is private. Each keyword changes the access control from that point on to
the end of the class or until the next access control keyword. Class declarations
end with a closing brace and a semicolon. Example 1</P>
<PRE><FONT COLOR="#0066FF">class Cat
{
public:
unsigned int Age;
unsigned int Weight;
void Meow();
};

Cat  Frisky;
Frisky.Age = 8;
Frisky.Weight = 18;
Frisky.Meow();</FONT></PRE>
<P><BR>
Example</P>
<PRE><FONT COLOR="#0066FF">class Car
{
public:                            // the next five are public

void Start();

⌨️ 快捷键说明

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