Hello, C + + (32) class is an abstraction and description of the real World 6.2. Class 1 declarations and definitions

Source: Internet
Author: User
Tags naming convention


Class 6.2: When C + + falls in love with object-oriented


The concept of class is the embodiment of object-oriented thought in C + +: It is both the result of encapsulation and the carrier of inheritance and polymorphism. Therefore, to learn the object-oriented programming in C + +, you must start with "class".


Declaration and definition of the 6.2.1 class


Object-oriented thinking regards everything in the real world as an object, whereas a class is an abstraction of all objects of the same type, a description of them as a whole. For example, the school has a lot of teachers, Zhang, teacher Li, Mr. Wang, although each teacher is different, is the individual object. But they are teachers of this type of object, have a common attribute (all have name, title) and the same behavior (all can class, correcting homework). We abstract the common attributes and the same behavior of a certain type of object, describe them with variables and functions, and then encapsulate these variables and functions in the concept of class, which is a new type of data that can be used to describe such objects, and this new type of data is also called a class. In C + +, the syntax for declaring a class is as follows:

class class name
{
public:
    // Public members, usually used to describe the same behavior of such objects
protected:
    // Protected members
private:
    // Private members, usually used to describe the common attributes of such objects
}; // Note that there is a semicolon to indicate the end of the class
Among them, class is a keyword used to declare a class in C ++, followed by the name of the class to be declared, usually a noun that can summarize this type of object. The naming convention is similar to the variable naming convention introduced earlier. Here, we want to define a class to describe such objects as "teacher", so we use "Teacher" as the name of this class.

In the following chapters, we will also learn that the classes in C ++ are divided into base classes and derived classes, which is the embodiment of the inheritance mechanism of object-oriented thinking in the class. If this class is inherited from a base class, we must add the inheritance method of this class (public, protected, or private) and the name of the base class it inherits after "class class name". In this way, the syntax format for declaring a class becomes accordingly:

class class name: inheritance method base class name
{
    // Declaration of member variables and member functions ...
};
If a class has no inheritance relationship, the inheritance method in the class declaration can be omitted. The Teacher class here is the base class itself, not inherited from other classes, so the inheritance method should be omitted here.

After completing the definition of the class name and inheritance relationship, you can begin to describe the properties and behavior of the class in the body of the class. The attributes of an object belong to data, so we define some variables in the class declaration to describe the attributes of the object. For example, objects like "teacher" have the attribute name, so we can define a variable strName of type string to describe it. These variables describe the properties of the object and become an integral part of this class, so they are also called member variables.

Best practice: Initializing member variables in class declarations

If some member variables of the class have initial values, we can declare these member variables in the class and give it an initial value, so that during runtime, the class can directly use the initial value to complete the corresponding member before entering the constructor Initialization of variables. E.g:

class Teacher
{
// Member variable with initial value
protected:
    // Use the string constant "Name" as the initial value of the member variable m_strName
    string m_strName = "Name"; // name
private:
    // Use the constant 2000 as the initial value of the member variable m_unBaseSalary
    unsigned int m_unBaseSalary = 2000;
};
In this code, we use two constants as the initial values of the two member variables m_strName and m_unSalary of the class. After such a declaration, there is no need to perform additional initialization in the constructor when creating an object of this class, and its two member variables will have corresponding initial values. This feature can be used when all objects of all classes have the same initial value. For example, the "m_unBaseSalary" of all "Teacher" objects is 2000 yuan.

In addition to declaring member variables to describe the properties of an object, another important part of an object is its behavior. In C ++, we use functions to describe a behavior. Similarly, we also introduce functions into the class as its member functions to describe the behavior of class objects. For example, if a "teacher" object has a lesson preparation action, we can add a PrepareLesson () function to the teacher class. In this function, we can specifically define the teacher preparation action. The composition of classes is shown in 6-7.

 

                       

Figure 6-7 Composition of classes

Best practice: Design programmer-friendly interfaces for classes

The class we designed is not only for our own use, but more often it will be provided to other programmers to achieve code reuse or team collaboration. At this time, the quality of the interface design of the class will affect whether others can use the class we designed correctly and easily. Therefore, it has also become an important criterion for measuring the level of a programmer.

The interface of the class, just like the instruction manual of the class, is to explain to the user of the class the resources it needs and the services it can provide. As long as the interface of the class is friendly to the programmer, the interface can easily know how to use the class correctly. To do this, the following design principles should be followed.

l Follow the naming rules of variables and functions

Member variables are also variables, and member functions are also functions. Therefore, as the interface of the class, they should also follow the general naming rules when naming, so that their names can accurately and concisely express their meaning.

l Simplified class view

Interfaces represent the services that classes can provide to users. Therefore, when designing the interface of the class, you only need to make the necessary member functions public, and use protected or private members to hide unnecessary details from the user. Because it hides content that users should not access, it naturally reduces the chance of users making mistakes.

l Use user's vocabulary

The design of the class is ultimately for users to use, so when designing the interface of the class, you should use the familiar vocabulary from the user's perspective, so that the user does not need to learn new vocabulary or concepts when reading the interface of the class This can smooth the user's learning curve and make our classes easier to use.

In addition to defining variables and functions in the class to represent the attributes and behavior of the class, you can also use the three keywords public, protected, and private to modify these members and specify their access level. According to different access levels, all members of the class are divided into three parts. Generally, members decorated with public can be accessed from outside. We will define the behavior of the class in the public section and provide public function interfaces for external access; members decorated with protected are only accessible by the class itself and its derived classes, so in the protected section , We can define the attributes and behaviors inherited to the next generation subclasses; finally, the privately modified members can only be accessed by the class itself, so in the private section, we can define the attributes and behaviors that are private to this class. The inheritance method and access control of the class will be described in detail later. Let's first look at a practical example. For example, to define a class to describe a class of objects such as teachers, through the abstraction of such objects, we find that objects such as teachers have name attributes that only themselves and subclasses can access and class behavior that everyone can access. Of course, teachers have many other attributes and behaviors, which are simplified here as needed. Finally, we use an object-oriented encapsulation mechanism to bind these attributes and behaviors together, and we have a teacher class declaration.

// teacher
class Teacher
{
// member function
// describe the behavior of the object
public: // Public part for external access
    void GiveLesson (); // Class
// Member variables
// Describe the properties of the object
protected: // protected part, self and subclass access
    string m_strName; // name
private:
};
Through this code, we declare a Teacher class, which is an abstract description of all teachers such objects. This class has a member function GiveLesson () modified by the public keyword, which represents that objects such as teachers have a behavior that everyone can access-class. It also has a variable m_strName modified by the protected keyword, which means that the only attribute that the teacher and other objects can access is name. In this way, by declaring a function in a class to describe the behavior of the object, and declaring a variable to describe the property of the object, a class that can be used to describe a certain type of object is completely declared.

After completing the declaration of the class, we also need to define the behavior of the class. The specific definition of the class member function can be completed at the same time when the member function is declared directly in the class:

class Teacher
{
// member function
// describe the behavior of the object
public:
    // Declare the member function while completing its definition
    void GiveLesson ()
    {
        cout << "Teacher is in class." << endl;
    };

// ...

};
More often, we just put the class declaration in the header file (for example, Teacher.h file), and put the specific implementation of the member function in the external definition of the class, which is the corresponding source file (for example, Teacher.cpp )in. When defining a member function of a class outside the class, we need to introduce the header file where the class declaration is located in the source file, and use the "::" domain operator to indicate the class to which the function belongs before the function name. E.g:

#ifndef _TEACHER_H // Define the header file macro to prevent the header file from being repeatedly introduced
#define _TEACHER_H // We will introduce it in detail later in section 7.3.1
// Declaration file of class Teacher.h
class Teacher
{
    //…
public:
    void GiveLesson (); // Only declare, not define
};

#endif


// Definition file of Teacher.cpp class
// Introduce the header file where the class declaration is located
#include "Teacher.h"
// Complete the definition of member functions outside the Teacher class
void Teacher :: GiveLesson ()
{
    cout << "Teacher is in class." << endl;
}
Here you can see that the definition of member functions is the same as ordinary functions. They also use functions to complete certain actions, but member functions represent the actions of certain types of objects. For example, here is just outputting a string representing the teacher's actions in class. Of course, in practical applications, class member functions can also access member variables, and the completed actions are much more complicated than this.

 

Know more: Another keyword used to declare classes in C ++-struct

In C ++, to declare a class, in addition to using the genuine "class" keyword, the "struct" keyword used to define the structure introduced in Section 3.8 can also be used to declare a class. Grammatically, "class" and "struct" are very similar, both can be used to declare a class, and the only difference between the two is that, by default, without specifying the access level, the class declared with "class" Members are private, and members of classes declared with "struct" are public. E.g:

// Use "struct" to define a Rect class
struct Rect
{
    // No access permission description
// Member functions of the class, public by default (public)
    int GetArea ()
    {
        return m_nW * m_nH;
    }

    // Member variables of the class, which are also public by default (public)
    int m_nW;
    int m_nH;
};
Here, we use "struct" to declare a Rect class, because no public and other keywords are used to explicitly indicate the access control of class members. By default, class members are public, so they can be accessed directly. E.g:

Rect rect;
// Direct access to member variables
rect.m_nH = 3;
rect.m_nW = 4;

// Direct access to member functions
The area of cout << "Rect is:" << rect.GetArea () << endl;
The default access control of these two keywords is either too conservative or too open. This "one size fits all" approach obviously cannot be adapted to all situations. So whether we use "class" or "struct" to declare a class, we should clearly indicate the appropriate access level of each member in the declaration, and should not rely on the default behavior of keywords.

"Class" and "struct" in addition to the above differences in the default access level of class members, from the "feel" speaking, most programmers think they are still different: "struct" is just like a bunch of lack of encapsulation The open memory bit is more often used to represent more complex data; while the "class" is more like a living and reliable real entity, it can provide services, have a solid encapsulation mechanism and a well-defined interface. Since everyone is so "feeling", it is only when the class has few methods and there is more public data that the "struct" keyword is used to declare the class; otherwise, the "class" keyword is more appropriate.

Hello, C ++ (32) class is an abstraction and description of the real world 6.2.1 Class declaration and definition

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.