📄 apa.htm
字号:
objects of class Lot_size are declared. On lines 36 through line 38, the values ofthe objects are set using the set() method. An important point to note is that theclass Tax_assessment has no objects in the main() method, so you cannot access anydata member or method of this class from main().</P><P>On line 41, the area of the Lot_size is output by operating the get_area() methodon an object of class Lot_size. On line 42, the city taxes are output by operatingthe method get_data2 on an object of Lot_size. This approach is required becausethe city_tax is a member data of class Tax_assessment, which cannot be operated ondirectly in the main() method. You use the method get_data2, which is a method ofLot_size and has access to the object taxes, which in turn can be accessed via get_city_tax.</P><P><H2><A NAME="Heading9"></A>Inheritance</H2><P>One of the advantages of programming in C++ or any other object-oriented languageis taking a global to local approach. Suppose you need to develop a program thatcomprehends all metals and their characteristics. If you take the class approachof the previous section, you would probably have one class named metals. The datamembers of metals would probably be density and volume. You could have another classnamed gold and one for aluminum. The data members describing gold and aluminum wouldneed all the properties of metals in addition to their own data members such as colorand shine. If you could devise a hierarchy of classes such that the classes for goldand aluminum would have only their individual data members but inherit the genericproperties from the parent metals class--then you would be using inheritance.</P><P>Inheritance is also called derivation. The new class inherits the functionalityof an existing class. The existing class is called the base class, and the new classis called the derived class. A similar inheritance can be derived for animals, mammals,and dogs.</P><P>To derive a new class from a base class, you use the colon (:) operator:</P><P><PRE>class human : public mammal</PRE><P>In this example, the new class human is derived from the base class mammal. Thederived class human would have all the functionality of the base class mammal. Inaddition, the human class can have other functionality, such as the ability to drivea car and work for food. The example in Listing A.13 shows how to create the objectsof type human and access its data and functions.</P><P><H4>LISTING A.13. Inherit1.cpp.</H4><PRE> 1: // Workspace Name: Inherit 2: // Program Name : Inherit1.cpp 3: 4: #include <iostream.h> 5: enum GENDER { MALE, FEMALE }; 6: 7: class Mammal 8: { 9: public:10: // constructors11: Mammal():itsAge(35), itsWeight(180){}12: ~Mammal(){}13: 14: int GetAge()const { return itsAge; }15: void SetAge(int age) { itsAge = age; }16: int GetWeight() const { return itsWeight; }</PRE><PRE>17: void SetWeight(int weight) { itsWeight = weight; }</PRE><PRE>18: 19: 20: protected:21: int itsAge;22: int itsWeight;23: };24: 25: class Human : public Mammal26: {27: public:28: 29: // Constructors30: Human():itsGender(MALE){}31: ~Human(){}32: 33: GENDER GetGender() const { return itsGender; }34: void SetGender(GENDER gender) { itsGender = gender; }35: 36: void Drive() { cout << "Driving to work...\n"; }37: void Work() { cout << "working...\n"; }38: 39: private:40: GENDER itsGender;41: };42: 43: void main()44: {45: Human John_doe;46: John_doe.Drive();47: John_doe.Work();48: cout << "John_doe is " << John_doe.GetAge() << " years old\n";49: cout << "And weighs " <<John_doe.GetWeight() << " lbs \n";50: }</PRE><P>The output from Listing A.13 is shown in Figure A.12.</P><P><A HREF="javascript:popUp('0afig12.gif')"><B>FIGURE A.12.</B></A><B> </B><I>Inheritanceoutput.</I></P><P>On line 5, a new keyword enum is defined. Enumerate defines a new data type witha list of identifiers. The identifiers are fixed values that increment automatically.In this example, the variable MALE has a value 0 and the variable FEMALE has a value1 by default. You could also specify a value:</P><P><PRE>enum Alphabets ( A, B, C=5, D=1)</PRE><P>In this case, A has a value 0, B is 1, C is 5, and D is 1. If you did not specifyany values, then</P><P>A is 0</P><P>B is 1</P><P>C is 2</P><P>D is 3</P><P>On line 20, another new keyword protected is defined in the class Mammal. Youcovered public and private in the section on classes where all the data members weredefined under the private keyword. When the data member is defined as private, thederived class cannot access them. For the derived classes to be able to access thedata members and methods of a class, they must be defined as protected. The protectedkeyword restricts the access only to the derived classes. Another alternative isto define these methods and members as public, in which case all classes have freeaccess. Although this is a solution, it is not a desired solution because it movesyou away from encapsulation.</P><P>Line 7 declares the base class Mammal. The constructor is on line 11, and thedestructor is on line 12. In classes, whenever an object of the class is created,the class constructor is called. The constructor class performs an additional functionof initializing its member data, itsAge(35) and itsWeight(180). This could have beenaccomplished by initializing the member data in the body of the constructor, as shownin the following:</P><P><PRE>Mammal(){itsAge = 35;itsWeight = 180;};</PRE><P>The technique of initializing the data members in the constructor declaration(as shown on line 11 of Listing A.14) is far more efficient due to the internal initializationof classes in C++. Use this technique whenever possible because it increases codeefficiency.</P><P>With derived classes, when an object is created in the derived class, the constructorof the base class is called first and then the constructor of the derived class iscalled. In this example, when the object John_doe is created for the first time,the constructor of the base class Mammal is called. The object John_doe is not createduntil both the base constructor and derived class constructor are called. With destructors,the reverse order is followed; when the object John_doe ceases to exist, the derivedclass destructor is called before the base class destructor. On line 25, you definethe name of the derived class and its relevant base class.</P><P>Line 48 and line 49 are critical in terms of how the data is accessed and output.On lines 48 and 49, the Human object John_doe accesses information directly fromthe base class of Mammal. Remember from the example class3.cpp, to output data froma nested class, you had to use indirect access to the class Tax_assessment.</P><P>Inheritance is a significant tool in object-oriented programming, and if it'sused effectively, it provides code reusability. The inherit1.cpp program gave youan overall flavor of inheritance and its properties. However, when programs are writtenin real life, they are structured more efficiently. The next program involves a morelogical and formal process of writing a program.</P><P>Assume you are writing a program for the automobile market. The automobile marketconsists of cars, trucks, minivans, and SUVs (sport utility vehicles). automobileis the parent or base class, and the others are the derived classes. Let's startby defining the automobile class. Listing A.14 shows the code.</P><P><H4>LISTING A.14. Auto.h.</H4><PRE> 1: // Workspace name: Inherit2 2: // Program name: Auto.h 3: 4: #ifndef AUTO_H 5: #define AUTO_H 6: 7: class automobile 8: { 9: protected:10: int miles_per_gallon;</PRE><PRE>11: float fuel_capacity;</PRE><PRE>12: public:13: void initialize(int in_mpg, float in_fuel);14: int get_mpg(void);15: float get_fuel(void);16: float travel_distance(void);17: }18: 19: #endif</PRE><P>Lines 4 and 5 include directives to the preprocessor. The directive on line 4is covered in detail toward the end of this section. On line 7, the class automobileis defined. This class has two data members and four methods. The class is includedin the header file only. The definition of the methods of this class are containedin the Auto.cpp file in Listing A.15.</P><P><H4>LISTING A.15. Auto.cpp.</H4><PRE> 1: // Workspace name : Inherit2 2: // Program name : Auto.cpp 3: #include "auto.h" 4: 5: 6: void automobile::initialize(int in_mpg, float in_fuel) 7: { 8: miles_per_gallon = in_mpg; 9: fuel_capacity = in_fuel;10: }11: 12: // Get the rated fuel economy - miles per gallon13: int automobile::get_mpg()14: {15: return miles_per_gallon;16: }17: 18: // Get the fuel tank capacity19: float automobile::get_fuel()20: {21: return fuel_capacity;22: }23: 24: // Return the travel distance possible25: float automobile::travel_distance()26: {27: return miles_per_gallon * fuel_capacity;28: }</PRE><P>The method get_mpg provides the value for the miles per gallon for a particularvehicle. The get_fuel<I> </I>method provides the gas tank capacity. Next, you definethe first derived class, a car, in Listing A.16.</P><P><H4>LISTING A.16. Car.h.</H4><PRE> 1: // Workspace name: Inherit2 2: // Program name: Car.h 3: 4: #ifndef CAR_H 5: #define CAR_H 6: 7: #include "auto.h" 8: 9: class car : public automobile 10: {11: int Total_doors;12: public:13: void initialize(int in_mpg, float in_fuel, int door = 4);14: int doors(void);15: };16: 17: #endif</PRE><P>The class car is a derived class from the automobile class. Because it is a derivedclass, it has access to all of the methods of the base class automobile. In addition,this class has a data member for the number of doors in the car. The methods of thisclass are defined in Car.cpp in Listing A.17.</P><P><H4>LISTING A.17. Car.cpp.</H4><PRE> 1: // Workspace name: Inherit2 2: // Program name: Car.cpp 3: 4: #include "car.h" 5: 6: void car::initialize(int in_mpg, float in_fuel, int door) 7: { 8: Total_doors = door;</PRE><PRE> 9: miles_per_gallon = in_mpg;</PRE><PRE>10: fuel_capacity = in_fuel;11: }12: 13: 14: int car::doors(void)15: {16: return Total_doors;17: }</PRE><P>The initialization method is defined in lines 6 through 11. It is important tonote that the base class of the automobile (auto.h) also had an initialization method.The initialization in the car class overrides the base class initialization. Lastbut not least is the main() definition. The main() method is defined in Allauto.cppin Listing A.18.</P><P><H4>LISTING A.18. Allauto.cpp.</H4><PRE> 1: // Workspace name: Inherit2 2: // Program name: Allauto.cpp 3: 4: #include <iostream.h> 5: #include "auto.h" 6: #include "car.h" 7: 8: int main() 9: {10: 11: car sedan;12: 13: sedan.initialize(24, 20.0, 4);14: cout << "The sedan can travel " << sedan.travel_distance() << 15: " miles.\n";16: cout << "The sedan has " << sedan.doors() << " doors.\n";17: 18: return 0;19: }</PRE><P>The main() definition has only one object defined. On line 11, an object of classcar is declared. The initialization is on line 13. The initialization passes thefuel efficiency of the car (miles per gallon) and the tank capacity. This informationis used to access the method travel_distance in the base class define in auto.cpp.The derived class has access to the methods of the base class. Additionally, thederived class passes information to its own data member about the number of doorsin the vehicle. The result of executing this program is shown in Figure A.13.</P><P><A HREF="javascript:popUp('0afig13.gif')"><B>FIGURE A.13.</B></A><B> </B><I>Vehicleclass results.</I></P><P>You can now add more classes for other vehicle types. You can make your own classesfor a truck and minivan and derive them from the base class exactly like the carclass.</P><P>If you add another class for trucks, it is important to include the preprocessordirectives from Listing A.14's lines 4 and 19. These lines are listed again in thefollowing:</P><P><PRE>4 #ifndef AUTO.H5 #define AUTO.H...19 #endif</PRE><P>Because the truck class is derived from the parent class automobile, it must includethe file Auto.h in Truck.h. The header of the car class, Car.h, already includesAuto.h for the same reason. Now, if you create a method that uses both the truckand car classes, you could potentially include Auto.h twice, which would generatein a compiler error. To prevent this, you add lines 4 and 5 of Listing A.14. Line4 issues a command to the compiler to verify whether the class AUTO.H has been defined;if it hasn't been defined, the program jumps to line 5 and defines it, and if ithas been defined, the program jumps to line 19 and ends.</P><P><H2><A NAME="Heading10"></A>Summary</H2><P>Congratulations! You have covered almost all of the features and properties ofC++. You should now have a sol
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -