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

📄 ch06.htm

📁 good book for learning c++ standard language
💻 HTM
📖 第 1 页 / 共 5 页
字号:
void Accelerate();
void Brake();
void SetYear(int year);
int GetYear();

private:                           // the rest is private

int Year;
Char Model [255];
};                                 // end of class declaration

Car OldFaithful;                   // make an instance of car
int bought;                        // a local variable of type int
OldFaithful.SetYear(84) ;          // assign 84 to the year
bought = OldFaithful.GetYear();    // set bought to 84
OldFaithful.Start();               // call the start method
</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 Class
Methods</FONT></H3>
<P>As you've seen, an accessor function provides a public interface to the private
member data of the class. Each accessor function, along with any other class methods
that you declare, must have an implementation. The implementation is called the function
definition.</P>
<P>A member function definition begins with the name of the class, followed by two
colons, the name of the function, and its parameters. Listing 6.3 shows the complete
declaration of a simple <TT>Cat</TT> class and the implementation of its accessor
function and one general class member function.</P>

<P><A NAME="Heading22"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.3. Implementing
the methods of a simple class.</B></FONT><FONT COLOR="#0066FF"></FONT>
<PRE><FONT COLOR="#0066FF">1:   // Demonstrates declaration of a class and
2:   // definition of class methods,
3:
4:   #include &lt;iostream.h&gt;      // for cout
5:
6:   class Cat                   // begin declaration of the class
7:   {
8:     public:                   // begin public section
9:       int GetAge();           // accessor function
10:      void SetAge (int age);  // accessor function
11:      void Meow();            // general function
12:    private:                  // begin private section
13:      int itsAge;             // member variable
14:  };
15:
16:  // GetAge, Public accessor function
17:  // returns value of itsAge member
18:  int Cat::GetAge()
19:  {
20:     return itsAge;
21:  }
22:
23:  // definition of SetAge, public
24:  // accessor function
25:  // returns sets itsAge member
26:  void Cat::SetAge(int age)
27:  {
28:     // set member variable its age to
29:     // value passed in by parameter age
30:     itsAge = age;
31:  }
32:
33:  // definition of Meow method
34:  // returns: void
35:  // parameters: None
36:  // action: Prints &quot;meow&quot; to screen
37:  void Cat::Meow()
38:  {
39:     cout &lt;&lt; &quot;Meow.\n&quot;;
40:  }
41:
42:  // create a cat, set its age, have it
43:  // 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 definition
of the <TT>Cat</TT> class. Line 8 contains the keyword <TT>public</TT>, which tells
the compiler that what follows is a set of public members. Line 9 has the declaration
of the public accessor method <TT>GetAge()</TT>. <TT>GetAge()</TT> provides access
to the private member variable <TT>itsAge</TT>, which is declared in line 13. Line
10 has the public accessor function <TT>SetAge()</TT>. <TT>SetAge()</TT> takes an
integer 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 line
13 of the private member variable <TT>itsAge</TT>. The class declaration ends with
a closing brace and semicolon in line 14.</P>
<P>Lines 18-21 contain the definition of the member function <TT>GetAge()</TT>. This
method takes no parameters; it returns an integer. Note that class methods include
the class name followed by two colons and the function name (Line 18). This syntax
tells the compiler that the <TT>GetAge()</TT> function that you are defining here
is the one that you declared in the <TT>Cat</TT> class. With the exception of this
header 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 to
the public method<TT> GetAge()</TT>. Because <TT>GetAge()</TT> is a member function
of the <TT>Cat</TT> class, it has full access to the <TT>itsAge</TT> variable. This
access 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 takes
an integer parameter and sets the value of <TT>itsAge</TT> to the value of that parameter
in line 30. Because it is a member of the <TT>Cat</TT> class, <TT>SetAge()</TT> has
direct access to the member variable <TT>itsAge</TT>.</P>
<P>Line 37 begins the definition, or implementation, of the <TT>Meow()</TT> method
of 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 prints
a 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> is
assigned to the <TT>itsAge</TT> member variable by way of the <TT>SetAge()</TT> accessor
method. 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 message
using the <TT>GetAge()</TT> accessor. Line 51 calls <TT>Meow()</TT> again.
<H3 ALIGN="CENTER"><A NAME="Heading24"></A><FONT COLOR="#000077">Constructors and
Destructors</FONT></H3>
<P>There are two ways to define an integer variable. You can define the variable
and then assign a value to it later in the program. For example,</P>
<PRE><FONT COLOR="#0066FF">int Weight;            // define a variable
...                    // other code here
Weight = 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 your
variable is never without a meaningful value.</P>
<P>How do you initialize the member data of a class? Classes have a special member
function called a constructor. The constructor can take parameters as needed, but
it cannot have a return value--not even <TT>void</TT>. The constructor is a class
method 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 clean
up after your object and free any memory you might have allocated. A destructor always
has the name of the class, preceded by a tilde (<TT>~</TT>). Destructors take no
arguments 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 Constructors
and Destructors</FONT></H4>
<P>If you don't declare a constructor or a destructor, the compiler makes one for
you. 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 are
called 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 the
parentheses 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 it
leaves 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 constructors
with no parameters can have a function body in which they initialize their objects
or 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 destructor
would 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 initialize
the <TT>Cat</TT> object, setting its age to whatever initial age you provide, and
it demonstrates where the destructor is called.</P>

<P><A NAME="Heading26"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.4. Using constructors
and destructors.</B></FONT><FONT COLOR="#0066FF"></FONT>
<PRE><FONT COLOR="#0066FF">1:   // Demonstrates declaration of a constructors and
2:   // destructor for the Cat class
3:
4:   #include &lt;iostream.h&gt;      // for cout
5:
6:   class Cat                   // begin declaration of the class
7:   {
8:    public:                    // begin public section
9:      Cat(int initialAge);     // constructor
10:     ~Cat();                  // destructor
11:     int GetAge();            // accessor function
12:     void SetAge(int age);    // accessor function
13:     void Meow();
14:   private:                   // begin private section
15:     int itsAge;              // member variable
16:  };
17:
18:  // constructor of Cat,
19:  Cat::Cat(int initialAge)
20:  {
21:     itsAge = initialAge;
22:  }
23:
24:  Cat::~Cat()                 // destructor, takes no action
25:  {
26:  }
27:
28:  // GetAge, Public accessor function
29:  // returns value of itsAge member
30:  int Cat::GetAge()
31:  {
32:     return itsAge;
33:  }
34:
35:  // Definition of SetAge, public
36:  // accessor function
37:
38:  void Cat::SetAge(int age)
39:  {
40:     // set member variable its age to
41:     // value passed in by parameter age
42:     itsAge = age;
43:  }
44:
45:  // definition of Meow method
46:  // returns: void
47:  // parameters: None
48:  // action: Prints &quot;meow&quot; to screen
49:  void Cat::Meow()
50:  {
51:     cout &lt;&lt; &quot;Meow.\n&quot;;
52:  }
53:
54:  // create a cat, set its age, have it
55   // 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();

⌨️ 快捷键说明

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