📄 ch06.htm
字号:
<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 intx = 5; // set x's value to 5</FONT></PRE><P>This is a shorthand way of saying, "Assign <TT>5</TT> to the variable <TT>x</TT>,which is of type <TT>int</TT>." 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> objectand 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 DeclareIt, 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,"This is Frisky. Frisky knows a trick. Frisky, bark." The child will giggleand say, "No, silly, cats can't bark."</P><P>If you wrote</P><PRE><FONT COLOR="#0066FF">Cat Frisky; // make a Cat named FriskyFrisky.Bark() // tell Frisky to bark</FONT></PRE><P>the compiler would say, <TT>No, silly, Cats can't bark</TT>. (Your compiler'swording 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 Friskymeow 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 importantare <TT>public</TT> and <TT>private</TT>.</P><P>All members of a class--data and methods--are private by default. Private memberscan be accessed only within methods of the class itself. Public members can be accessedthrough 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 meansthat 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, "I'llaccess <TT>itsAge</TT>, <TT>itsWeight</TT>, and <TT>Meow()</TT> only from withinmember functions of the <TT>Cat</TT> class." 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 meanthat 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 hearyou yelling, "Hey! I just said Boots is a cat. Why can't Boots access his ownage?" 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. Accessingthe public members of a simple class.</B></FONT><FONT COLOR="#0066FF"></FONT></P><PRE><FONT COLOR="#0066FF">1: // Demonstrates declaration of a class and2: // definition of an object of the class,3:4: #include <iostream.h> // for cout5:6: class Cat // declare the class object7: {8: public: // members which follow are public9: int itsAge;10: int itsWeight;11: };12:13:14: void main()15: {16: Cat Frisky;17: Frisky.itsAge = 5; // assign to the member variable18: cout << "Frisky is a cat who is " ;19: cout << Frisky.itsAge << " years old.\n";<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 nameof 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 witha 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 inline 16 as an instance of a <TT>Cat</TT>--that is, as a <TT>Cat</TT> object. <TT>Frisky</TT>'sage is set in line 17 to <TT>5</TT>. In lines 18 and 19, the <TT>itsAge</TT> membervariable 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 DataPrivate</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 andget the private member variables. These accessor methods are the member functionsthat 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 simplerand 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 storedfrom how it is used. This enables you to change how the data is stored without havingto 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 arriveat the age. The calling function doesn't need to know whether you are storing itas 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 longerlife 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 dataand 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 classwith accessor methods.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1: // Cat class declaration2: // Data members are private, public accessor methods3: // mediate setting and getting the values of the private data4:5: class Cat6: {7: public:8: // public accessors9: unsigned int GetAge();10: void SetAge(unsigned int Age);11:12: unsigned int GetWeight();13: void SetWeight(unsigned int Weight);14:15: // public member functions16: Meow();17:18: // private member data19: 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 13contain the accessor methods for <TT>itsWeight</TT>. These accessor functions setthe 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 performsanother 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, asin</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 mistakesbefore they become bugs. Any programmer worth his consulting fees can find a wayaround privacy if he wants to. Stroustrup, the inventor of C++, said, "The C++access control mechanisms provide protection against accident--not against fraud."(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 collectionof class member data, which are variables of various types, including other classes.The class also contains class functions--or methods--which are functions used tomanipulate the data in the class and to perform other services for the class. Youdefine 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 classmembers and functions by using the dot (<TT>.</TT>) operator. You use access controlkeywords to declare sections of the class as public or private. The default for accesscontrol is private. Each keyword changes the access control from that point on tothe end of the class or until the next access control keyword. Class declarationsend 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 publicvoid Start();void Accelerate();void Brake();void SetYear(int year);int GetYear();private: // the rest is privateint Year;Char Model [255];}; // end of class declarationCar OldFaithful; // make an instance of carint bought; // a local variable of type intOldFaithful.SetYear(84) ; // assign 84 to the yearbought = OldFaithful.GetYear(); // set bought to 84OldFaithful.Start(); // call the start method
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -