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

📄 ch06.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 5 页
字号:
</FONT></PRE><BLOCKQUOTE>	<P><HR><B>DO </B>declare member variables private. <B>DO</B> use public accessor methods.	<B>DON'T</B> try to use private member variables from outside the class. <B>DO</B>	access private member variables from within class member functions. <HR></BLOCKQUOTE><H3 ALIGN="CENTER"><A NAME="Heading21"></A><FONT COLOR="#000077">Implementing ClassMethods</FONT></H3><P>As you've seen, an accessor function provides a public interface to the privatemember data of the class. Each accessor function, along with any other class methodsthat you declare, must have an implementation. The implementation is called the functiondefinition.</P><P>A member function definition begins with the name of the class, followed by twocolons, the name of the function, and its parameters. Listing 6.3 shows the completedeclaration of a simple <TT>Cat</TT> class and the implementation of its accessorfunction and one general class member function.</P><P><A NAME="Heading22"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.3. Implementingthe methods of a simple class.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:   // Demonstrates declaration of a class and2:   // definition of class methods,3:4:   #include &lt;iostream.h&gt;      // for cout5:6:   class Cat                   // begin declaration of the class7:   {8:     public:                   // begin public section9:       int GetAge();           // accessor function10:      void SetAge (int age);  // accessor function11:      void Meow();            // general function12:    private:                  // begin private section13:      int itsAge;             // member variable14:  };15:16:  // GetAge, Public accessor function17:  // returns value of itsAge member18:  int Cat::GetAge()19:  {20:     return itsAge;21:  }22:23:  // definition of SetAge, public24:  // accessor function25:  // returns sets itsAge member26:  void Cat::SetAge(int age)27:  {28:     // set member variable its age to29:     // value passed in by parameter age30:     itsAge = age;31:  }32:33:  // definition of Meow method34:  // returns: void35:  // parameters: None36:  // action: Prints &quot;meow&quot; to screen37:  void Cat::Meow()38:  {39:     cout &lt;&lt; &quot;Meow.\n&quot;;40:  }41:42:  // create a cat, set its age, have it43:  // meow, tell us its age, then meow again.44:  int main()45:  {46:     Cat Frisky;47:     Frisky.SetAge(5);48:     Frisky.Meow();49:     cout &lt;&lt; &quot;Frisky is a cat who is &quot; ;50:     cout &lt;&lt; Frisky.GetAge() &lt;&lt; &quot; years old.\n&quot;;51:     Frisky.Meow();52;      return 0;<TT>53: }</TT>Output: Meow.Frisky is a cat who is 5 years old.Meow.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Lines 6-14 contain the definitionof the <TT>Cat</TT> class. Line 8 contains the keyword <TT>public</TT>, which tellsthe compiler that what follows is a set of public members. Line 9 has the declarationof the public accessor method <TT>GetAge()</TT>. <TT>GetAge()</TT> provides accessto the private member variable <TT>itsAge</TT>, which is declared in line 13. Line10 has the public accessor function <TT>SetAge()</TT>. <TT>SetAge()</TT> takes aninteger as an argument and sets <TT>itsAge</TT> to the value of that argument.<BR>Line 11 has the declaration of the class method <TT>Meow()</TT>. <TT>Meow()</TT>is not an accessor function. Here it is a general method that prints the word <TT>Meow</TT>to the screen.</P><P>Line 12 begins the private section, which includes only the declaration in line13 of the private member variable <TT>itsAge</TT>. The class declaration ends witha closing brace and semicolon in line 14.</P><P>Lines 18-21 contain the definition of the member function <TT>GetAge()</TT>. Thismethod takes no parameters; it returns an integer. Note that class methods includethe class name followed by two colons and the function name (Line 18). This syntaxtells the compiler that the <TT>GetAge()</TT> function that you are defining hereis the one that you declared in the <TT>Cat</TT> class. With the exception of thisheader line, the <TT>GetAge()</TT> function is created like any other function.</P><P>The <TT>GetAge()</TT> function takes only one line; it returns the value in <TT>itsAge</TT>.Note that the <TT>main()</TT> function cannot access <TT>itsAge</TT> because <TT>itsAge</TT>is private to the <TT>Cat</TT> class. The<TT> main()</TT> function has access tothe public method<TT> GetAge()</TT>. Because <TT>GetAge()</TT> is a member functionof the <TT>Cat</TT> class, it has full access to the <TT>itsAge</TT> variable. Thisaccess enables <TT>GetAge()</TT> to return the value of <TT>itsAge</TT> to <TT>main()</TT>.</P><P>Line 26 contains the definition of the <TT>SetAge()</TT> member function. It takesan integer parameter and sets the value of <TT>itsAge</TT> to the value of that parameterin line 30. Because it is a member of the <TT>Cat</TT> class, <TT>SetAge()</TT> hasdirect access to the member variable <TT>itsAge</TT>.</P><P>Line 37 begins the definition, or implementation, of the <TT>Meow()</TT> methodof the <TT>Cat</TT> class. It is a one-line function that prints the word <TT>Meow</TT>to the screen, followed by a new line. Remember that the <TT>\n</TT> character printsa new line to the screen.</P><P>Line 44 begins the body of the program with the familiar <TT>main()</TT> function.In this case, it takes no arguments and returns <TT>void</TT>. In line 46, <TT>main()</TT>declares a <TT>Cat</TT> named <TT>Frisky</TT>. In line 47, the value <TT>5</TT> isassigned to the <TT>itsAge</TT> member variable by way of the <TT>SetAge()</TT> accessormethod. Note that the method is called by using the class name (<TT>Frisky</TT>)followed by the member operator (<TT>.</TT>) and the method name (<TT>SetAge()</TT>).In this same way, you can call any of the other methods in a class.</P><P>Line 48 calls the <TT>Meow()</TT> member function, and line 49 prints a messageusing the <TT>GetAge()</TT> accessor. Line 51 calls <TT>Meow()</TT> again.<H3 ALIGN="CENTER"><A NAME="Heading24"></A><FONT COLOR="#000077">Constructors andDestructors</FONT></H3><P>There are two ways to define an integer variable. You can define the variableand then assign a value to it later in the program. For example,</P><PRE><FONT COLOR="#0066FF">int Weight;            // define a variable...                    // other code hereWeight = 7;            // assign it a value</FONT></PRE><P>Or you can define the integer and immediately initialize it. For example,</P><PRE><FONT COLOR="#0066FF">int Weight = 7;        // define and initialize to 7</FONT></PRE><P>Initialization combines the definition of the variable with its initial assignment.Nothing stops you from changing that value later. Initialization ensures that yourvariable is never without a meaningful value.</P><P>How do you initialize the member data of a class? Classes have a special memberfunction called a constructor. The constructor can take parameters as needed, butit cannot have a return value--not even <TT>void</TT>. The constructor is a classmethod with the same name as the class itself.</P><P>Whenever you declare a constructor, you'll also want to declare a destructor.Just as constructors create and initialize objects of your class, destructors cleanup after your object and free any memory you might have allocated. A destructor alwayshas the name of the class, preceded by a tilde (<TT>~</TT>). Destructors take noarguments and have no return value. Therefore, the <TT>Cat</TT> declaration includes</P><PRE><FONT COLOR="#0066FF">~Cat();</FONT></PRE><H4 ALIGN="CENTER"><A NAME="Heading25"></A><FONT COLOR="#000077">Default Constructorsand Destructors</FONT></H4><P>If you don't declare a constructor or a destructor, the compiler makes one foryou. The default constructor and destructor take no arguments and do nothing.</P><P>What good is a constructor that does nothing? In part, it is a matter of form.All objects must be constructed and destructed, and these do-nothing functions arecalled at the right time. However, to declare an object without passing in parameters,such as</P><PRE><FONT COLOR="#0066FF">Cat Rags;           // Rags gets no parameters</FONT></PRE><P>you must have a constructor in the form</P><PRE><FONT COLOR="#0066FF">Cat();</FONT></PRE><P>When you define an object of a class, the constructor is called. If the <TT>Cat</TT>constructor took two parameters, you might define a <TT>Cat</TT> object by writing</P><PRE><FONT COLOR="#0066FF">Cat Frisky (5,7);</FONT></PRE><P>If the constructor took one parameter, you would write</P><PRE><FONT COLOR="#0066FF">Cat Frisky (3);</FONT></PRE><P>In the event that the constructor takes no parameters at all, you leave off theparentheses and write</P><PRE><FONT COLOR="#0066FF">Cat Frisky ;</FONT></PRE><P>This is an exception to the rule that states all functions require parentheses,even if they take no parameters. This is why you are able to write</P><PRE><FONT COLOR="#0066FF">Cat Frisky;</FONT></PRE><P>which is a call to the default constructor. It provides no parameters, and itleaves off the parentheses. You don't have to use the compiler-provided default constructor.You are always free to write your own constructor with no parameters. Even constructorswith no parameters can have a function body in which they initialize their objectsor do other work.</P><P>As a matter of form, if you declare a constructor, be sure to declare a destructor,even if your destructor does nothing. Although it is true that the default destructorwould work correctly, it doesn't hurt to declare your own. It makes your code clearer.</P><P>Listing 6.4 rewrites the <TT>Cat</TT> class to use a constructor to initializethe <TT>Cat</TT> object, setting its age to whatever initial age you provide, andit demonstrates where the destructor is called.</P><P><A NAME="Heading26"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.4. Using constructorsand destructors.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:   // Demonstrates declaration of a constructors and2:   // destructor for the Cat class3:4:   #include &lt;iostream.h&gt;      // for cout5:6:   class Cat                   // begin declaration of the class7:   {8:    public:                    // begin public section9:      Cat(int initialAge);     // constructor10:     ~Cat();                  // destructor11:     int GetAge();            // accessor function12:     void SetAge(int age);    // accessor function13:     void Meow();14:   private:                   // begin private section15:     int itsAge;              // member variable16:  };17:18:  // constructor of Cat,19:  Cat::Cat(int initialAge)20:  {21:     itsAge = initialAge;22:  }23:24:  Cat::~Cat()                 // destructor, takes no action25:  {26:  }27:28:  // GetAge, Public accessor function29:  // returns value of itsAge member30:  int Cat::GetAge()31:  {32:     return itsAge;33:  }34:35:  // Definition of SetAge, public36:  // accessor function37:38:  void Cat::SetAge(int age)39:  {40:     // set member variable its age to41:     // value passed in by parameter age42:     itsAge = age;43:  }44:45:  // definition of Meow method46:  // returns: void47:  // parameters: None48:  // action: Prints &quot;meow&quot; to screen49:  void Cat::Meow()50:  {51:     cout &lt;&lt; &quot;Meow.\n&quot;;52:  }53:54:  // create a cat, set its age, have it55   // meow, tell us its age, then meow again.56:  int main()57:  {58:    Cat Frisky(5);59:    Frisky.Meow();60:    cout &lt;&lt; &quot;Frisky is a cat who is &quot; ;61:    cout &lt;&lt; Frisky.GetAge() &lt;&lt; &quot; years old.\n&quot;;62:    Frisky.Meow();63:    Frisky.SetAge(7);64:    cout &lt;&lt; &quot;Now Frisky is &quot; ;65:    cout &lt;&lt; Frisky.GetAge() &lt;&lt; &quot; years old.\n&quot;;66;     return 0;<TT>67: }</TT></FONT><FONT COLOR="#0066FF">Output: Meow.Frisky is a cat who is 5 years old.Meow.Now Frisky is 7 years old.</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis:</B></FONT><B> </B>Listing 6.4 is similar to6.3, except that line 9 adds a constructor that takes an integer. Line 10 declaresthe destructor, which takes no parameters. Destructors never take parameters, andneither constructors nor destructors return a value--not even <TT>void</TT>.<BR>Lines 19-22 show the implementation of the constructor. It is similar to the implementationof the <TT>SetAge()</TT> accessor function. There is no return value.</P><P>Lines 24-26 show the implementation of the destructor <TT>~Cat()</TT>. This functiondoes nothing, but you must include the definition of the function if you declareit in the class declaration.</P><P>Line 58 contains the definition of a <TT>Cat</TT> object, <TT>Frisky</TT>. Thevalue <TT>5</TT> is passed in to <TT>Frisky</TT>'s constructor. There is no needto call <TT>SetAge()</TT>, because Frisky was created with the value <TT>5</TT> inits member variable <TT>itsAge</TT>, as shown in line 61. In line 63, Frisky's <TT>itsAge</TT>

⌨️ 快捷键说明

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