Hello, the C ++ (36) ginseng is good and cannot be used as a meal! How are the 6.3 categories object-oriented?

Source: Internet
Author: User

Hello, the C ++ (36) ginseng is good and cannot be used as a meal! How are the 6.3 categories object-oriented?
How is class 6.3 object-oriented?

Class is a product of the combination of C ++ and object-oriented thinking. as a carrier of Object-oriented Thinking in C ++, it is subject to object-oriented blood. From the composition of Class Members to the inheritance relationship between classes to virtual functions, there are three main features of object-oriented encapsulation, inheritance and polymorphism.

6.3.1 implement encapsulation using the class Mechanism

Considering this practical problem, there are multiple teachers in the school. Each teacher's name, age, and other attributes are different, but these teachers will prepare lessons and have the same behavior. So how do we show these teachers in the program? Although there are many individual teachers, they all belong to the same class of things-teachers. In C ++, we use the concept of class to describe a class of things, and abstraction is the first process of this process. Abstract is generally divided into two types: attribute abstraction and Behavior Abstraction. The former looks for the common attributes of a type of things. For example, teachers all have data describing the status of things such as age and name, and then use variables to express them. For example, use the m_nAge variable to express age, the m_strName variable is used to express the name, while the latter is used to look for the common behaviors of such things. For example, the teacher prepares lessons and classes, and then expresses them using functions, such as PrepareLesson () the function expresses the instructor's course preparation behavior, and uses the GiveLesson () function to express the class behavior. It can also be seen from here that the entire abstract process is a process from a specific (teacher) to a general (variable and function.

If abstraction extracts the common attributes and behaviors of similar things and expresses them using variables and functions, the encapsulation mechanism binds them together to form a complete class. In the C ++ language, we can use the class concept introduced in section 6.2 to encapsulate the variables and functions obtained from analysis and make them a member of the class, this represents the attributes and behaviors of such things. For example, things like teachers can be encapsulated:

// Use the Teacher class to encapsulate the instructor's attributes and behavior class Teacher {// constrfunction public: // construct the instructor object Teacher (string strName) {m_strName = strName ;}; // use the member function to describe the instructor's behavior. public: void PrepareLesson (); // prepare the course void GiveLesson (); // class void ReviewHomework (); // correct the assignment // other member functions... // Use member variables to describe the instructor's attributes protected: string m_strName; // name int m_nAge; // age bool m_bMale; // gender int m_nDuty; // Title private :};

Through encapsulation, the attributes and behaviors shared by teachers and other things can be closely combined in the Teacher class to form a reusable data type. From the actual Teacher to the Teacher class, it is a process from concrete to abstract. Now with the abstract Teacher class, you can use it to define an object, then we use this object to describe a specific teacher. This is a process from abstraction to concrete. For example:

// Define a Teacher Class Object to describe a Teacher in the school, Teacher MrChen ("ChenLiangqiao"); // Teacher MrWang ("WangGang"), a Teacher in the school ");

Although MrChen and MrWang are both Teacher objects, they can describe two different teachers in the real world because of their different attributes.

By encapsulating classes, you can also hide attributes and behaviors of things. Due to access control restrictions, the outside world cannot directly hide the information of the class. For some sensitive data in the class, we can set it to the protection or private type, in this way, you can avoid accidental modification and hide the data. On the other hand, encapsulated classes provide services externally through specific external interfaces (Public member functions. In this process, the outside world only sees the name of the service interface and the required parameters, but does not know how these interfaces are actually implemented inside the class. In this way, the specific implementation details of the interface are well hidden from the outside, and the service interface that is most concerned about the outside is provided directly to it. In this way, classes hide behaviors, as shown in Figure 6-10.

 

Figure 6-10 abstraction and Encapsulation

Abstraction and encapsulation are used to transform things in the real world into various classes in the C ++ world, that is, to describe the real world using programming languages. Process-oriented thinking also has an abstract process, but its abstraction only targets real-world processes. The abstraction of object-oriented thinking not only includes the data of things, but also the behavior of things, furthermore, object-oriented uses encapsulation to organically combine data and behavior to form classes, so as to reflect the real world more realistically. Abstraction and encapsulation have completed the process from specific things in the real world to classes in the C ++ world. This is the first step and the most important step to program the real world.

6.3.2 use the base class and derived class to implement inheritance

After understanding how the class mechanism implements the encapsulation feature of Object-oriented Thinking, continue to analyze the above example. In the real world, we find that teachers and students share the same attributes and behaviors, such as names, ages, and genders, can walk, speak, eat and so on. Why do different things share the same attributes and behaviors? This is because these features are shared by humans, and teachers and students are sub-categories of humans, so they all share the attributes and actions of these humans. Similar to this seed category, the parent category has the same attributes and behaviors. For example, cars and trucks are sub-categories of automobiles. They all have the common attributes (engines) and behaviors (driving) of automobiles. televisions and refrigerators are sub-categories of household appliances, they all have a common property (electricity) and behavior (Enabled) of household appliances ).

In C ++, we use classes to represent a class of other things. Since the Parent and Child classes may have the same attributes and behaviors, this means that the parent class and child classes should have a large number of identical member variables and member functions. So, do these identical members need to be defined once in both parent and child classes? Apparently not. C ++ provides an Inheritance Mechanism to describe the relationship between a parent class and a subcategory in the real world. The class that represents the parent class is called the base class or parent class, and the class that represents the subclass inherited from the base class is called the derived class or subclass. Inheritance allows us to make more specific descriptions or extensions based on the original features of the parent class to form a new subclass. For example, if you can say that "A teacher is the person who will attend classes", you can let the teacher sub-class inherit from the parent class. for members who represent the common attributes and behaviors of humans, the instructor class is obtained directly from human inheritance without being defined again, and then added to the instructor subclass a function that uniquely represents class behavior. through inheritance and development, we have gained a class of teacher who has both common attributes and behaviors of humans and unique behaviors of teachers.

Inheritance is to obtain the wealth derived from the father. In the real world, this wealth may be gold and silver jewelry, or a simple family style. In the C ++ world, this wealth is the member variable and member function of the parent class. Through inheritance, child classes can easily have members of the parent class. More importantly, inheritance can further refine or expand the members of the parent class to meet new requirements and form a new class. In this way, when the old class is used to form a new class, you only need to inherit from the old class, and then modify or expand the required members. With the Inheritance Mechanism, C ++ can not only improve development efficiency, but also respond to changing needs. Therefore, it has become a powerful weapon to eliminate the "software crisis.

Let's look at a practical example. In the real world, there is such an "inheritance Tree", as shown in 6-11.

 

Figure 6-11 inheritance relationships in the real world

From this inheritance tree, we can see that both teachers and students inherit from humans. In this way, teachers and students have the attributes and behaviors of humans, primary School Students, middle school students, and college students inherit from the students. They not only have the attributes and behaviors of people, but also the attributes and behaviors of students. Through inheritance, the derived class does not need to repeatedly design and implement the existing attributes and behaviors of the base class. As long as it directly inherits the attributes and behaviors of the base class, in this way, the design and code can be reused to the maximum extent.

In C ++, the declaration of a derived class is as follows:

Class derived class name: Inheritance Method Base class Name 1, inheritance method base class name 2...

{

// Newly added attributes and behaviors of the derived class...

};

The derived class name is the name of the new class to be defined, and the base class name is the name of the defined class. A class can inherit multiple classes at the same time. If there is only one base class, this is called single inheritance. If there are multiple base classes, it is called multi-inheritance, at this time, the derived class can get the features of multiple base classes at the same time, just as we have both father features and mother features. However, we need to note that multi-inheritance may bring about the ambiguity of Members, because the two base classes may have members of the same name. If both are inherited into the derived classes, then, two members with the same name will appear in the derived class. In this way, when the Members from the base class are accessed through the member name in the derived class, they do not know which base class is accessed, this leads to the ambiguity of the program. Therefore, multi-inheritance is used only when it is necessary. More often, we use single-inheritance.

Similar to access control for class members, there are three inheritance Methods: public, protected, and private. Different inheritance methods determine how the derived class accesses the members inherited from the base class, reflecting the relationship between the derived class and the base class:

(1) public.

Public inheritance is called type inheritance. It indicates that the derived class is a subtype of the base class. The public and protected type members in the base class are directly inherited from the derived class along with their access level without any change. The public Member in the base class is also a public member in the derived class, and the protected member in the base class is also a protected member in the derived class. Public inheritance reflects a "is-a" relationship between the derived class and the base class, that is, the relationship between the parent class and the subclass. For example, if the instructor is a person (Teacher is-a Human), the Teacher class should inherit from the Human class in the public mode. The relationship between the parent category and sub-category reflected by public is very common in the real world, from biological evolution to organizational system, which can be expressed by public inheritance, therefore, it is also the most common inheritance method in C ++.

(2) private.

Private inheritance is called implementation inheritance. It converts the public and protected members of the base class into their own private members. In this way, the derived class no longer supports the public interfaces of the base class, it only hopes to reuse the implementation of the base class. Private inheritance reflects the use... If Class A private inherits from Class B, it is only because Class A needs to use some existing code of Class B but does not want to add an interface of Class, it does not indicate the conceptual relationship between Class A and Class B. In this sense, private inheritance is purely an implementation technology and meaningless for design.

(3) protected.

Protected inheritance changes the public and protected type members of the base class into their own protected type members, so as to protect all public interfaces of the base class from being accessed by the outside and only by themselves and their own derived classes. Therefore, when we need to inherit the members of a base class and allow these Members to inherit from the next generation of derived classes without exposing the public members of the base class, you can use the protected inheritance method.

After learning about the declaration method of the derived class, you can use the specific code to describe the inheritance relationship expressed in the inheritance tree above.

// Defines the common behavior of the base class Humanclass Human {// Human, which can be accessed by the outside world. // The access level is set to public: void Walk (); // walk void Talk (); // speaking // common human attributes // It must be inherited from a derived class to prevent external access, // set the access level to protected type protected: string m_strName; // name int m_nAge; // age bool m_bMale; // gender private: // no private member }; // The relationship between Teacher and Human is "is-a". // Therefore, Teacher uses the public Inheritance Method to inherit Humanclass Teacher: public Human {// Add the teacher's specific behavior in the subclass public: void PrepareLesson (); // prepare the class void GiveLesson (); // class void ReviewHomework (); // correct the assignment // Add the instructor-specific attribute protected: int m_nDuty In the subclass; // position private :}; // the student is also a human, the public Inheritance Method inherits the Human class Student: public Human {// Add the Student's specific behavior in the subclass public: void AttendClass (); // class void DoHomework (); // do homework // Add the student's unique attribute protected: int m_nScore In the subclass; // The exam score is private:}; // the pupil is a student, therefore, the public Inheritance Method inherits the Student class Pupil: public Student {// Add the unique behavior of primary school students to the subclass public: void PlayGame (); // play the void WatchTV (); // watch TV public: // redefine void DoHomework (); protected: private:} for "doing a job :};

In this Code, we first declare the basic class "Human", which defines the common attributes (names, ages, and gender) that people and other things should have) and behavior (walking and talking ). Because the Teacher is a kind of Human and the embodiment of the class of Human, we define the derived class of Teacher in the form of public inheritance based on Human. Through inheritance, the Teacher class not only directly has members of the public and protected type in the Human class, but also adds the attributes (positions) specific to the Teacher class as needed) and behavior (preparing lessons and attending classes). This completes the inheritance and expansion of the Human class, and the Teacher class is a "Human who will prepare lessons and attend classes ".

// Define a Teacher object Teacher MrChen; // The instructor walks into the classroom // We have not defined the Walk () member function in the Teacher class, // here, the member function MrChen obtained from the base class Human is inherited. walk (); // The instructor starts class. // here, the member function MrChen defined by Teacher is called. giveLesson ();

Similarly, we also inherit the Human class through public, and add the unique attributes (m_nScore) and behaviors (AttendClass () and DoHomwork () of students to define the Student class. Furthermore, the Student class inherits more specific Pupil classes in the same way as needed to represent primary school students. Through inheritance, we can completely and clearly express the entire "inheritance tree.

After careful consideration, we will find that the entire inheritance process is the process of constantly externalizing the class, inheriting the attributes and behaviors of the base class, and developing its own special attributes and behaviors. In the real world, the species evolve to absorb and retain part of the parent generation through the child generation, and at the same time, according to environmental changes, improve the capabilities of the parent generation and add new capabilities to form new species. Inheritance is the embodiment of this evolutionary process in the real world in the procedural world. Therefore, the evolution of classes also follows similar rules:

(1) Keep the attributes and behaviors of the base class.

The biggest purpose of inheritance is to reuse the design and implementation of the base class and retain the attributes and behaviors of the base class. For a derived class, you don't have to start from scratch. Everything starts from scratch. As long as you inherit from the class, it directly becomes the "rich generation" with rich attributes and behaviors of the base class ". In the above example, the derived class Teacher inherits the Human base class and easily owns all the public and Protection Type members of the Human class. This is like standing on the shoulders of giants, the Teacher class only uses a small amount of code to possess attributes such as names, ages, and behaviors inherited from the base class, as well as walking and speaking. This achieves design and code reuse.

(2) Improve the attributes and behaviors of the base class.

Since it is an evolution, the derived class must have a better place than the base class, which is manifested in the modification of the base class members by the derived class. For example, the Student class has a DoHomework () member function that indicates the act of "doing a job". The Pupil class of the derived class directly inherits the Student class and also owns this member function. However, primary School Students do their jobs in a special way. The base class defined DoHomework () function cannot meet its needs. Therefore, the derived class Pupil had to redefine the DoHomework () member function, so as to further embody it according to its actual situation and rewrite it to meet new requirements. In this way, both the base class and the derived class have the DoHomework () member function, but this function in the derived class is more specific and more targeted after rewriting, and is an improvement to the base class.

(3) Add new attributes and actions.

If evolution only improves the original things, it is far from enough. Evolution also requires some revolutionary content to create new things. Therefore, in class inheritance, the derived class can not only improve the attributes and behaviors of the base class, more importantly, add some new "revolutionary" attributes and actions to make them a new class. For example, the Teacher Class is derived from the Human class, which retains the attributes and behaviors of the base class, and adds new attributes (positions) not available to the base class as needed) and behavior (preparing lessons and attending classes) are just the newly added attributes and behaviors that make it essentially different from the Human class and complete the evolution from Human to Teacher.

Obviously, inheritance not only effectively solves the problem of design and code reuse-derived class inheritance retains the attributes and behaviors of the base class, at the same time, it provides an extension method to easily cope with new requirements-Derived classes can change the behavior of the base class and add new attributes and behaviors as needed, this is the charm of Object-oriented thinking.

Since inheritance can bring so many benefits, you can reuse the previous design and code without any effort, can inheritance be used wherever inheritance can be used, and the more it is, the better?

Of course not. Good ginseng, cannot be used as a meal. Because inheritance is too useful and brings many benefits, it is often abused by beginners. In the end, it leads to the design of some "Four unlike" monsters. Here, we need to set several rules for the inheritance:

(1) only two classes with relevance can inherit.

If two classes (A and B) are irrelevant, B cannot inherit A to make B more functional. That is to say, it is not allowed to let "man" have "flight" behavior, and let "man" derive from "bird", then what we get is no longer "man ", it's a "bird. Do not think that the more functions the better. Here, we should stick to the principle of "more than one thing, less than one thing.

(2) do not consider a combination as inheritance.

If Class B needs to use the services provided by Class A, consider the following two situations:

1) B is the "One" of ". Logically, if B is A kind of a, B is allowed to inherit. For example, a Teacher (Teacher) is a kind of Human. It is a special embodiment of Human, so Teacher can inherit from Human.

2) A is A "part" of B ". Logically, if A is a part of B, although the two are also correlated, B is not allowed to inherit from. For example, a keyboard or display is part of a computer.

If B cannot inherit A, but A is A "part" of B, and B needs to use the service provided by A, what should I do? Make the object of A member of B and combine it with other objects to Form B. In this way, the object of A can be accessed in B, and the services provided by A can naturally be obtained. For example, a computer requires a keyboard input service and a display output service, while a keyboard and a display are part of a computer, and the computer cannot be derived from a keyboard or a display, then we can take the keyboard and display objects as computer member variables and get the services they provide:

// Keyboard class Keyboard {public: // receives the user's Keyboard Input void Input () {cout <"Keyboard Input" <endl ;}}; // Display class Monitor {public: // Display screen void Display () {cout <"Display output" <endl ;}; // Computer class Computer {public: // use the Keyboard and display to combine a Computer (Keyboard * pKeyboard, Monitor * pMonitor) {m_pKeyboard = pKeyboard; m_pMonitor = pMonitor ;} // The computer's behavior // The specific actions are completed by each component. // the keyboard is responsible for user Input void Input () {m_pKeyboard-> Input ();} // The Display is responsible for displaying the image void Display () {m_pMonitor-> Display ();} // private: Keyboard * m_pKeyboard = nullptr; // Keyboard Monitor * m_pMonitor = nullptr; // display // other component objects}; int main () {// create the keyboard and display object Keyboard first; Monitor monitor; // combine the keyboard and display object into Computer com (& keyboard, & monitor); // the input and output of the Computer are actually handed over to the keyboard and display to complete com. input (); com. display (); return 0 ;}

In the code above, the computer class consists of objects of the Keybord and Monitor classes (of course, there should be more components in specific practices ), all its functions are not implemented by itself, but are transferred to the specific implementation of each component object. It only provides a unified external interface. The combination of several class objects to form a new class is a combination. Although the computer does not inherit the keyboard and display, in combination, the computer also obtains the services provided by the keyboard and display, with the input and output functions. Note that object pointers are used as class member variables to combine objects because the computer is a pluggable system, both the keyboard and display can be changed. The keyboard can be used on this computer or another computer. The lifecycles of the computer and keyboard are different. Therefore, the object pointer is used as a member variable. The two objects can be independently created and combined, or split and used separately. However, if the whole and part are inseparable, the two have the same life cycle, such as the arm and thigh of a person and the person who makes up the whole person, in this case, the object should be directly used as the member variable. For example:

// Arm class Arm {public: // Arm-provided service, embracing void Hug () {cout <"Hug by hand" <endl ;}}; // foot class Leg {public: // foot service, Walk void Walk () {cout <"Walking with feet" <endl ;}}; // Body class Body {public: // the services provided by the Body are handed over to each part of the Body to complete void Hug () {arm. hug ();} void Walk () {leg. walk ();} private: // each part of the Body, because they share the same lifecycle with the Body, // here we use the object as the class member variable Arm; leg leg ;}; int main () {// when creating the Body object, it also creates an Arm and Leg Object Body; // use the services provided by the Body. These services are ultimately completed by the Arm and Leg that constitute the Body. hug (); body. walk (); // when the Body object is destroyed, the Arm and Leg objects that constitute it are also destroyed. return 0 ;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.