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

📄 ch06.htm

📁 Why C++ is the emerging standard in software development. The steps to develop a C++ program. How
💻 HTM
📖 第 1 页 / 共 5 页
字号:
void SetWeight(int aWeight);};</FONT></PRE><P>Listings 6.6 and 6.7 re-create the <TT>Cat</TT> class, but they put the declarationin <TT>CAT.HPP</TT> and the implementation of the functions in <TT>CAT.CPP</TT>.Listing 6.7 also changes the accessor functions and the <TT>Meow()</TT> functionto inline.</P><P><A NAME="Heading35"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.6. Cat classdeclaration in CAT.HPP</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:  #include &lt;iostream.h&gt;2:  class Cat3:   {4:  public:5:   Cat (int initialAge);6:   ~Cat();7:    int GetAge() { return itsAge;}             // inline!8:    void SetAge (int age) { itsAge = age;}     // inline!9:    void Meow() { cout &lt;&lt; &quot;Meow.\n&quot;;}             // inline!10:  private:11: int itsAge;<TT>12: };</TT></FONT></PRE><P><A NAME="Heading37"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.7. Cat implementationin CAT.CPP</B></FONT><FONT SIZE="2" COLOR="#000077"><B>.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:   // Demonstrates inline functions2:   // and inclusion of header files3:4:   #include &quot;cat.hpp&quot;  // be sure to include the header files!5:6:7:   Cat::Cat(int initialAge)   //constructor8:   {9:      itsAge = initialAge;10:  }11:12:  Cat::~Cat()             //destructor, takes no action13:  {14:  }15:16:  // Create a cat, set its age, have it17:  // meow, tell us its age, then meow again.18:  int main()19:  {20:     Cat Frisky(5);21:     Frisky.Meow();22:     cout &lt;&lt; &quot;Frisky is a cat who is &quot; ;23:     cout &lt;&lt; Frisky.GetAge() &lt;&lt; &quot; years old.\n&quot;;24:     Frisky.Meow();25:     Frisky.SetAge(7);26:     cout &lt;&lt; &quot;Now Frisky is &quot; ;27:     cout &lt;&lt; Frisky.GetAge() &lt;&lt; &quot; years old.\n&quot;;28:      return 0;<TT>29: }</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>The code presented in Listing 6.6and Listing 6.7 is similar to the code in Listing 6.4, except that three of the methodsare written inline in the declaration file and the declaration has been separatedinto <TT>CAT.HPP</TT>.<BR><TT>GetAge()</TT> is declared in line 7, and its inline implementation is provided.Lines 8 and 9 provide more inline functions, but the functionality of these functionsis unchanged from the previous &quot;outline&quot; implementations.</P><P>Line 4 of Listing 6.7 shows <TT>#include &quot;cat.hpp&quot;</TT>, which bringsin the listings from <TT>CAT.HPP</TT>. By including <TT>cat.hpp</TT>, you have toldthe precompiler to read <TT>cat.hpp</TT> into the file as if it had been typed there,starting on line 5.</P><P>This technique allows you to put your declarations into a different file fromyour implementation, yet have that declaration available when the compiler needsit. This is a very common technique in C++ programming. Typically, class declarationsare in an <TT>.HPP</TT> file that is then <TT>#includ</TT>ed into the associatedCPP file.</P><P>Lines 18-29 repeat the main function from Listing 6.4. This shows that makingthese functions inline doesn't change their performance.<H3 ALIGN="CENTER"><A NAME="Heading38"></A><FONT COLOR="#000077">Classes with OtherClasses as Member Data</FONT></H3><P>It is not uncommon to build up a complex class by declaring simpler classes andincluding them in the declaration of the more complicated class. For example, youmight declare a wheel class, a motor class, a transmission class, and so forth, andthen combine them into a car class. This declares a has-a relationship. A car hasa motor, it has wheels, and it has a transmission.</P><P>Consider a second example. A rectangle is composed of lines. A line is definedby two points. A point is defined by an x-coordinate and a y-coordinate. Listing6.8 shows a complete declaration of a <TT>Rectangle</TT> class, as might appear in<TT>RECTANGLE.HPP</TT>. Because a rectangle is defined as four lines connecting fourpoints and each point refers to a coordinate on a graph, we first declare a <TT>Point</TT>class, to hold the x,y coordinates of each point. Listing 6.9 shows a complete declarationof both classes.</P><P><A NAME="Heading40"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.8. Declaringa complete class.</B></FONT><FONT COLOR="#0066FF"></FONT><PRE><FONT COLOR="#0066FF">1:   // Begin Rect.hpp2:   #include &lt;iostream.h&gt;3:   class Point     // holds x,y coordinates4:   {5:      // no constructor, use default6:      public:7:         void SetX(int x) { itsX = x; }8:         void SetY(int y) { itsY = y; }9:         int GetX()const { return itsX;}10:        int GetY()const { return itsY;}11:     private:12:        int itsX;13:        int itsY;14:  };    // end of Point class declaration15:16:17:  class  Rectangle18:  {19:     public:20:        Rectangle (int top, int left, int bottom, int right);21:        ~Rectangle () {}22:23:        int GetTop() const { return itsTop; }24:        int GetLeft() const { return itsLeft; }25:        int GetBottom() const { return itsBottom; }26:        int GetRight() const { return itsRight; }27:28:        Point  GetUpperLeft() const { return itsUpperLeft; }29:        Point  GetLowerLeft() const { return itsLowerLeft; }30:        Point  GetUpperRight() const { return itsUpperRight; }31:        Point  GetLowerRight() const { return itsLowerRight; }32:33:        void SetUpperLeft(Point Location)  {itsUpperLeft = Location;}34:        void SetLowerLeft(Point Location)  {itsLowerLeft = Location;}35:        void SetUpperRight(Point Location)  {itsUpperRight = Location;}36:        void SetLowerRight(Point Location)  {itsLowerRight = Location;}37:38:        void SetTop(int top) { itsTop = top; }39:        void SetLeft (int left) { itsLeft = left; }40:        void SetBottom (int bottom) { itsBottom = bottom; }41:        void SetRight (int right) { itsRight = right; }42:43:        int GetArea() const;44:45:     private:46:        Point  itsUpperLeft;47:        Point  itsUpperRight;48:        Point  itsLowerLeft;49:        Point  itsLowerRight;50:        int    itsTop;51:        int    itsLeft;52:        int    itsBottom;53:        int    itsRight;54:  };<TT>55: // end Rect.hpp</TT></FONT></PRE><P><A NAME="Heading42"></A><FONT SIZE="4" COLOR="#000077"><B>Listing 6.9. RECT.CPP.</B></FONT></P><PRE><FONT COLOR="#0066FF">1:   // Begin rect.cpp2:   #include &quot;rect.hpp&quot;3:   Rectangle::Rectangle(int top, int left, int bottom, int right)4:   {5:         itsTop = top;6:         itsLeft = left;7:         itsBottom = bottom;8:         itsRight = right;9:10:        itsUpperLeft.SetX(left);11:        itsUpperLeft.SetY(top);12:13:        itsUpperRight.SetX(right);14:        itsUpperRight.SetY(top);15:16:        itsLowerLeft.SetX(left);17:        itsLowerLeft.SetY(bottom);18:19:        itsLowerRight.SetX(right);20:        itsLowerRight.SetY(bottom);21:  }22:23:24:  // compute area of the rectangle by finding corners,25:  // establish width and height and then multiply26:  int Rectangle::GetArea() const27:  {28:        int Width = itsRight-itsLeft;29:        int Height = itsTop - itsBottom;30:        return (Width * Height);31:  }32:33:  int main()34:  {35:        //initialize a local Rectangle variable36:        Rectangle MyRectangle (100, 20, 50, 80 );37:38:        int Area = MyRectangle.GetArea();39:40:        cout &lt;&lt; &quot;Area: &quot; &lt;&lt; Area &lt;&lt; &quot;\n&quot;;41:        cout &lt;&lt; &quot;Upper Left X Coordinate: &quot;;42:        cout &lt;&lt; MyRectangle.GetUpperLeft().GetX();43:      return 0;<TT>44: }</TT>Output: Area: 3000Upper Left X Coordinate: 20</FONT></PRE><P><FONT COLOR="#000077"><B>Analysis: </B></FONT>Lines 3-14 in Listing 6.8 declarethe class <TT>Point</TT>, which is used to hold a specific x,y coordinate on a graph.As written, this program doesn't use <TT>Point</TT>s much. However, other drawingmethods require <TT>Point</TT>s.<BR>Within the declaration of the class <TT>Point</TT>, you declare two member variables(<TT>itsX</TT> and <TT>itsY</TT>) on lines 12 and 13. These variables hold the valuesof the coordinates. As the x-coordinate increases, you move to the right on the graph.As the y-coordinate increases, you move upward on the graph. Other graphs use differentsystems. Some windowing programs, for example, increase the y-coordinate as you movedown in the window.</P><P>The <TT>Point</TT> class uses inline accessor functions to get and set the <TT>X</TT>and <TT>Y</TT> points declared on lines 7-10. <TT>Point</TT>s use the default constructorand destructor. Therefore, you must set their coordinates explicitly.</P><P>Line 17 begins the declaration of a <TT>Rectangle</TT> class. A <TT>Rectangle</TT>consists of four points that represent the corners of the <TT>Rectangle</TT>.</P><P>The constructor for the <TT>Rectangle</TT> (line 20) takes four integers, knownas <TT>top</TT>,<TT> left</TT>,<TT> bottom</TT>, and <TT>right</TT>. The four parametersto the constructor are copied into four member variables (Listing 6.9) and then thefour <TT>Points</TT> are established.</P><P>In addition to the usual accessor functions, <TT>Rectangle</TT> has a function<TT>GetArea()</TT> declared in line 43. Instead of storing the area as a variable,the <TT>GetArea()</TT> function computes the area on lines 28-29 of Listing 6.9.To do this, it computes the width and the height of the rectangle, and then it multipliesthese two values.</P><P>Getting the x-coordinate of the upper-left corner of the rectangle requires thatyou access the <TT>UpperLeft</TT> point, and ask that point for its <TT>X</TT> value.Because <TT>GetUpperLeft()</TT>is <TT>()</TT>a method of <TT>Rectangle</TT>, it candirectly access the private data of <TT>Rectangle</TT>, including <TT>itsUpperLeft</TT>.Because <TT>itsUpperLeft</TT> is a <TT>Point</TT> and <TT>Point</TT>'s <TT>itsX</TT>value is private, <TT>GetUpperLeft()</TT> cannot directly access this data. Rather,it must use the public accessor function <TT>GetX()</TT> to obtain that value.</P><P>Line 33 of Listing 6.9 is the beginning of the body of the actual program. Untilline 36, no memory has been allocated, and nothing has really happened. The onlything you've done is tell the compiler how to make a point and how to make a rectangle,in case one is ever needed.</P><P>In line 36, you define a <TT>Rectangle</TT> by passing in values for <TT>Top</TT>,<TT>Left</TT>, <TT>Bottom</TT>, and <TT>Right</TT>.</P><P>In line 38, you make a local variable, <TT>Area</TT>, of type <TT>int</TT>. Thisvariable holds the area of the <TT>Rectangle</TT> that you've created. You initialize<TT>Area</TT> with the value returned by <TT>Rectangle</TT>'s <TT>GetArea()</TT>function.</P><P>A client of <TT>Rectangle</TT> could create a <TT>Rectangle</TT> object and getits area without ever looking at the implementation of <TT>GetArea()</TT>.</P><P><TT>RECT.HPP</TT> is shown in Listing 6.8. Just by looking at the header file,which contains the declaration of the <TT>Rectangle</TT> class, the programmer knowsthat <TT>GetArea()</TT> returns an <TT>int</TT>. How <TT>GetArea()</TT> does itsmagic is not of concern to the user of class <TT>Rectangle</TT>. In fact, the authorof <TT>Rectangle</TT> could change <TT>GetArea()</TT> without affecting the programsthat use the <TT>Rectangle</TT> class.<H3 ALIGN="CENTER"><A NAME="Heading44"></A><FONT COLOR="#000077">Structures</FONT></H3><P>A very close cousin to the <TT>class</TT> keyword is the keyword <TT>struct</TT>,which is used to declare a structure. In C++, a structure is exactly like a class,except that its members are public by default. You can declare a structure exactlyas you declare a class, and you can give it exactly the same data members and functions.In fact, if you follow the good programming practice of always explicitly declaringthe private and public sections of your class, there will be no difference whatsoever.</P><P>Try re-entering Listing 6.8 with these changes:<UL>	<LI>In line 3, change <TT>class Point</TT> to <TT>struct Point</TT>.	<P>	<LI>In line 17, change <TT>class Rectangle</TT> to <TT>struct Rectangle</TT>.</UL><P>Now run the program again and compare the output. There should be no change.<H4 ALIGN="CENTER"><A NAME="Heading45"></A><FONT COLOR="#000077">Why Two KeywordsDo the Same Thing</FONT></H4><P>You're probably wondering why two keywords do the same thing. This is an accidentof history. When C++ was developed, it was built as an extension of the C language.C has structures, although C structures don't have class methods. Bjarne Stroustrup,the creator of C++, built upon <TT>struct</TT>s, but he changed the name to <TT>class</TT>to represent the new, expanded functionality.<BLOCKQUOTE>	<P><HR><B>DO

⌨️ 快捷键说明

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