📄 apa.htm
字号:
<P>Let's start with describing the syntax and components of a class:</P><P><PRE><B>class</B> class_name{<B>public</B>:class_name_constructor;~class_name_destructor;class_method_prototypes();class_member_variables;<B>private</B>:class_method_prototypes();class_member_variables;};</PRE><P>The words in bold are keywords. You declare a class by using the class keyword.This is followed by the name of the class. The data and methods of a class are enclosedin curly brackets ({ }). The methods of a class are function prototypes. They determinethe behavior of the objects of your class. The member variables are the variablesin your class. Classes have constructors and destructors. The methods and variablescan be classified as either public or private.</P><P><PRE>You will now re-create the previous example of Struct.cpp in Listing A.8, employing the class and encapsulation methodology. The output from this program in Listing A.9 is identical to the previous example, Struct.cpp. </PRE><H4>LISTING A.9. Clasfarm.cpp.</H4><PRE> 1: // Workspace: Class2 2: // Program Name: Clasfarm.cpp 3: #include <iostream.h> 4: 5: class farm_house 6: { 7: int pig_values; 8: public: 9: void set(int input);10: int get(void);11: };12: 13: void farm_house::set(int input)14: {15: pig_values = input;16: }17: 18: int farm_house::get(void)19: {20: return pig_values;21: }22: 23: int main()24: {25: farm_house pig1, pig2, pig3;26: 27: 28: pig1.set(12);29: pig2.set(13);30: pig3.set(14);31: 32: cout << "The value of pig1 is " << pig1.get() << "\n";33: cout << "The value of pig2 is " << pig2.get() << "\n";34: cout << "The value of pig3 is " << pig3.get() << "\n";35: 36: return 0;37: 38: }</PRE><P>Compare the struct declaration of the Struct.cpp program in Listing A.8 (lines5 through 7) to the class declaration of the Clasfarm.cpp program in Listing A.9(lines 5 through 11). The difference is in the private and public portions of theirdeclarations. In the struct declaration, everything is public, whereas in the classdeclaration, you begin with a private section. All data and methods at the beginningof a class are private. This means the member variable</P><P><PRE>int pig_values; </PRE><P>is private and hidden to methods outside the class. This means that the variablepig_ values is not accessible inside main(). In other words, this member variableis hidden. This member variable is accessible to the methods of its class, mainly</P><P><PRE>void set (int input);int get(void);</PRE><P>These methods are defined to be public. Because they are public, these methodscan be accessed by any objects of this class. On line 25, you defined pig1, pig2,and pig3 to be instances or objects of the class. What? I am sure you are wonderingwhy pig1 is an object.</P><P>You defined on line 5 a class farm_house. Remember when you declare a class, allyou are doing is declaring a new type. When you declare a variable, you declare itstype and then the variable name, as shown here:</P><P><PRE>long somevariable, anotherone, onemore;</PRE><P>Similarly, to define an object of a class, you declare the type, which in thiscase is farm_house, and the object name, which is pig1:</P><P><PRE>farm_house pig1,pig2,pig3;</PRE><P>On line 28, you set the value of pig1 to 12. This is done using the dot operator(.). The object pig1 has access to the method set(). The set() method is a methodof the class farm_house, so it has access to its private data. The implementationof the set() method is shown on line 13. For the program to know that the set() methodis within the scope of the class farm_house, you use the scope (::) operator. Online 15, the variable input is set to the variable pig_values.</P><P>The class farm_house declared two public methods. The other method is the get()method. The get() method is implemented on line 18. The get() method takes no parametersbut only returns the pig_values because it also is within the scope of the classfarm_house.</P><P>On line 32, the get() method is again called by the objects pig1, pig2, and pig3to return the pig_values to the screen.</P><P>If you compare the two programs struct.cpp and clasfarm.cpp, you notice that oneis about 23 lines, whereas the other is 38 lines. The code just got longer by implementingclasses! This is true. The big benefits of using classes are really seen in morecomplex and larger programs. Also, because you hide critical data from the user,using classes is safer and less error prone. It enables the compiler to find mistakesbefore they become bugs.</P><P><H3><A NAME="Heading8"></A>Constructors and Destructors</H3><P>Earlier, I defined the syntax of a class. In the syntax, I mentioned constructorsand destructors. However, in the example clasfarm.cpp, you did not define any constructorsor destructors. If a constructor or a destructor is not defined, the compiler createsone for you.</P><P><H4>The Constructor Function</H4><P>A <I>constructor</I> is a class initialization function that is executed automaticallywhen a class instance is created. A constructor must abide by the following rules:</P><UL> <LI>The constructor must have the same name as its class name:</UL><PRE>class farm_house{public:farm_house(); //constructor..........}</PRE><UL> <LI>The constructor cannot be defined with a return value. <P> <LI>A constructor without any arguments is a default constructor. <P> <LI>The constructor must be declared with the public keyword.</UL><H4>The Destructor Function</H4><P>A destructor function is the opposite of a constructor function, which is executedautomatically when the block in which the object is initialized is exited. A destructorreleases the object and hence frees up the memory that was allocated. A destructormust abide by the following rules:</P><UL> <LI>The destructor must have the same name as the class. <P> <LI>The destructor function must be preceded by ~. <P> <LI>The destructor has neither arguments nor a return value. <P> <LI>The destructor function must be declared with the keyword public.</UL><PRE>class farm_house{public:farm_house (); // Constructor function~farm_house(); // Destructor function.....}</PRE><H4>Friend Functions and Friend Classes</H4><P>Methods and members that are declared private are accessible only to that partof the program that is part of the class. However, a function outside the class oranother class may be defined as a friend class or function. You can declare an entireclass or individual functions as friends. You must follow some critical rules whendeclaring friend functions:</P><UL> <LI>The use of friends should be kept to a minimum because it overrides the benefit of hiding the data. <P> <LI>Declaring x as a friend of y does not necessarily mean that y has access to the methods and members of x.</UL><H4>Class Declarations and Definitions</H4><P>Whenever you use classes, they have their own private and public member variablesand methods. As you saw in the previous Clasfarm.cpp example, the program is gettinglengthy. There are no hard rules, but there are some standard practices followedby almost all programmers. The procedure is to put all class declarations in theheader files. A header file is a file with an .h or .hpp extension. All the classdefinitions are placed in the .cpp file. The beginning of the .cpp file has an includedirective for the header file. For example, the clasfarm program would be separatedinto clasfarm.h and Clasfarm.cpp. The Clasfarm.h file would look like Listing A.10.</P><P><H4>LISTING A.10. Clasfarm.h.</H4><PRE> 1: // Workspace: Class2 2: // Program Name: Clasfarm.hpp 3: #include <iostream.h> 4: 5: class farm_house 6: { 7: int pig_values; 8: public: 9: void set(int input);10: int get(void);11: };</PRE><P>The Clasfarm.cpp file is in Listing A.11.</P><P><H4>LISTING A.11. Clasfarm.cpp.</H4><PRE> 1: #include <clasfarm.h> 2: void farm_house::set(int input) 3: { 4: pig_values = input; 5: } 6: 7: int farm_house::get(void) 8: { 9: return pig_values;10: }11: 12: int main()13: {14: farm_house pig1, pig2, pig3;15: 16: 17: pig1.set(12);18: pig2.set(13);19: pig3.set(14);20: 21: cout << "The value of pig1 is " << pig1.get() << "\n";22: cout << "The value of pig2 is " << pig2.get() << "\n";23: cout << "The value of pig3 is " << pig3.get() << "\n";24: 25: return 0;26: 27: };</PRE><H4>Classes Within a Class</H4><P>It is perfectly legal to have another class declaration within a given class.This is often referred to as nesting classes. The following example declares twoclasses, Lot_size and Tax_assessment. The Tax_assessment class object taxes is definedwithin the Lot_size class. The main() method has no objects of the Tax_assessmentclass, so the methods or members of the Tax_assessment class cannot be directly accessedfrom the main() function. Let's review the program in Listing A.12.</P><P><H4>LISTING A.12. Class3.cpp.</H4><PRE> 1: // Workspace Name: Class3 2: // Program Name: Class3.cpp 3: #include <iostream.h> 4: 5: class Tax_assessment 6: { 7: int city_tax; 8: int prop_tax; 9: public:</PRE><PRE>10: void set(int in_city, int in_prop)</PRE><PRE>11: {city_tax = in_city; prop_tax = in_prop; }12: int get_prop_tax(void) {return prop_tax;}13: int get_city_tax(void) {return city_tax;}14: };15: 16: 17: class Lot_size {18: int length;19: int width;20: Tax_assessment taxes;21: public:22: void set(int l, int w, int s, int p) {23: length = l; 24: width = w;25: taxes.set(s, p); }26: int get_area(void) {return length * width;}27: int get_data(void) {return taxes.get_prop_tax() ;}28: int get_data2(void) {return taxes.get_city_tax() ;}29: };30: 31: 32: int main()33: {34: Lot_size small, medium, large;35: 36: small.set(5, 5, 5, 25);37: medium.set(10, 10, 10, 50);38: large.set(20, 20, 15, 75);39: 40: 41: cout << "For a small lot of area "<< small.get_area ()<< "\n";42: cout << "the city taxes are $ "<< small.get_data2 () << "\n";43: cout << "and property taxes are $ " << small.get_data ()<< "\n";44: 45: cout << "For a medium lot of area "<< medium.get_area ()<< "\n";46: cout << "the city taxes are $ "<< medium.get_data2 () << "\n";47: cout << "and property taxes are $ " << medium.get_data ()<< "\n";48: 49: cout << "For a Large lot of area "<< large.get_area ()<< "\n";50: cout << "the city taxes are $ "<< large.get_data2 () << "\n";51: cout << "and property taxes are $ " << large.get_data ()<< "\n";52: return 0;53: }</PRE><P>When you execute this program, it outputs the area of an rectangle and also thehypothetical taxes on rectangular area. The output is shown in Figure A.11.</P><P><A HREF="javascript:popUp('0afig11.gif')"><B>FIGURE A.11.</B></A><B> </B><I>Outputfrom Class3.cpp.</I></P><P>In lines 5 through 14, the class Tax_assessment is defined. It consists of twoprivate data members, int city_tax and int prop_tax. The class has three public methods.It is important to note the declaration and definition of these methods. In the earlierexamples, you only declared the methods in the class. The function definitions wereaccessed using the scope (::) operator. In this example, you declare the method andalso write its definition. This technique is referred to as inline implementationof the function. If a function definition is small and concise, this is a good techniqueto employ. This technique is also used to increase program efficiency (speed of execution)because the program does not have to jump in and out of a function definition.</P><P>The data members city_tax and prop_tax are private so they can only be accessedvia their member methods--namely, set(), get_prop_tax(), and get_city_tax().</P><P>Lines 17 through 29 declare the class Lot_size with its data members and methods.On line 20, the class Tax_assessment is embedded in this class. The object taxesis also declared on this line, and it is under the privacy of the class Lot_size.The only methods that would be able to access this object are the ones belongingto the Lot_size class. The Lot_size class has four public methods declared and definedon line 22 and lines 26 through 28. Line 25 of the set() method has another set()method defined. This is not a recursive method but rather another example of functionoverloading. The set() method on line 10 and line 22 differ in the number of parameters.The set() method on line 25 can access the object taxes because it is defined underthe class Tax_assessment on line 20.</P><P>The main() function begins on line 32 and has a return type int. On line 34, the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -