C + + classes and objects in a detailed

Source: Internet
Author: User

        • What is a class
          • 1-1 development of the programming
          • 1-2 process-oriented to object orientation
          • Definition of Class 1-3
          • 1-4 Constructor destructor
        • Two memory management
          • 2-1 Memory Distribution
          • 2-2 Stacks and stacks
            • 2-2-1 Heap and Stack differences
            • 2-2-2 New and delete
        • Three-copy constructors
        • Combination of four classes
          • 4-1 what is a combination of classes
          • Constructors for class 4-2 combinations
        • Five inheritance
          • 5-1 Inheritance and derivation
          • 5-2 Constructor destructor when inheriting
          • 5-3 overriding the parent class method
        • Six polymorphism and virtual functions
          • 6-1 What is polymorphic
          • 6-2 Virtual functions
          • 6-3 pure virtual function and abstract class

I. What is the development of class 1-1 programming

?? We know that the development of the program has undergone about three stages: machine-oriented program design, process-oriented (structure) programming, object-oriented programming . The machine-oriented programming mainly uses the binary instruction or the assembly language to write the program. This method is easy to understand for the computer, but it is very painful for the program designer, it is not easy to read or design by the special training personnel, so it evolved the process-oriented design method.
?? Process-oriented This approach is similar to the way we normally think about problems, such as we need to wash clothes, according to our procedures to carry out the design process: remove clothes, pour water, washing powder, start rubbing and so on the steps, Then the function of each step is programmed to simulate the implementation. The language we use is representative of the C language. It's true that this approach is a great way to facilitate our programming, but as we evolve, we need to describe more and more complex processes, and engineering is getting bigger, and when we start a project again, we often need to start writing code from scratch, like washing coats we have a program, washing pants also has a program, But because the code is not reused or shared, we have to start writing a program from scratch. How can you enhance the reusability, flexibility, and extensibility of your code?
?? The new issue leads to our object-oriented programming (OOP), a computer programming architecture in which a basic principle is that a program is composed of a single unit or object that can act as a subroutine. This allows each object to accept information, process data, and send information to other objects for overall operations. Each unit can be used in other programs. In this way, OOP achieves the three main goals of software engineering: reusability, flexibility, extensibility is our C + + language, and of course the C + + language is also compatible with process-oriented.

1-2 process-oriented to object orientation

?? The object-oriented design method is how to implement our code reuse and extension? We know that in our process-oriented approach, we often do this:

 1. 对需要进行的功能设计对应的数据结构 2. 设计需要完成这种功能的算法

?? At this time our program structure is this: program = algorithm + data structure . So when we face a new problem often need to redesign the corresponding data structure, redesign the completion of this function of the algorithm. This allows code reusability to be relatively low.
?? When we use object-oriented approach to design programs, we often think like this:

 1. 这个整体对象有哪些子对象呢 2. 每一个子对象有什么属性和功能呢 3. 这些子对象是怎样联系起来的

?? So our design code is like this: object = algorithm + data structure; program = object + Object + object +
?? So we have a new problem, because there are already various objects that have completed sub-functions, so it is convenient to reuse the code.
?? Object-oriented objects are the basis, and classes are the objects we use to implement them, so classes are the basis of object-oriented. Class describes a set of objects that have the same attributes and the same behavior.

Definition of Class 1-3

?? In C + + programs We often separate the definition of a class from the definition of its member function, so that it is easy to read and code to write

1. 类定义可以看成类的外部接口,一般写成.h文件2. 类成员函数定义可以看成类的内部实现,一般写成.cpp文件

?? In our code, we typically define a class with a

?? For a class member function definition, we generally use the following format:

返回值 类名::函数名(参数列表){    函数体}

?? It is important to note that when there is no class name in front of the function: The compiler will assume that this is a normal function, because we do not describe which class the function is, and this also shows the scope of the function, in the scope of the class, member functions of a class have unrestricted access to data members of the same class.
?? Setting different access rights to different members of a class is the encapsulation of classes, which enhances security and simplifies programming, and the user does not have to know the specifics of the implementation, but only needs to use the exhausted members with specific access rights through the external interface.

1-4 Constructors, destructors

?? A constructor is a more important function in a class that is used primarily to create and initialize objects, which are called automatically by the system when an object is created. The constructor is the same as the class name, there is no return value, and the default is no parameter. The general form of the constructor is as follows:

class 类名{    public : 类名();}

Note: Constructors are non-parametric by default, but can be overloaded, that is, we can set parameters for constructors.
?? A constructor typically has three functions:

1. 分配空间,即在内存中分类该对象的使用空间2. 构造结构,构造整个类的结构3. 初始化,即对类中的属性进行初始化

?? Contrary to the constructor function is our destructor, the destructor of the main completion of the object before the removal of some cleanup work, at the end of the object life cycle of the system automatically call, and then release the object space. Destructors are added in front of the class name, no return value, no parameters, and unlike constructors, destructors cannot be refactored. The general form of the destructor is as follows:

class 类名{    public ~类名();}
Second, memory management 2-1 memory distribution

?? We know that after our class is constructed, we create space in memory to hold all kinds of data, and when the class life cycle ends, the system calls the destructor reclaim space, our class has constants, variables, functions, and so on, how is this data stored in memory?
?? The memory of a C + + program is generally divided into four zones,

?? It is important to note that the data collection in the heap and the stack is not the same, the operation of the heap memory, if allocated memory, it is responsible for recycling, otherwise it will cause memory leaks, functions in the stack allocated local variables, at the end of the function, will automatically reclaim and free space

2-2 Heap and Stack 2-2-1 heap and stack differences

?? To facilitate storage, the memory area is divided into heaps and stacks, both of which have different characteristics to store different data.
?? In general, heap space is relatively space relative to other memory spaces, so it gives the program a great degree of freedom to allocate space. However, it is not said that the heap of memory can be arbitrarily applied, the general use of heap space is the following:

 - 直到运行时才能知道需要多少对象空间 - 不知道对象的生存周期到底有多长 - 直到运行时才知道一个对象需要多少内存空间

?? Unlike the heap, when the program is created, the compiler is accurate until all the data length and the time of existence are saved in the stack. Due to the filo nature of the stack, the stack pointer moves down, creating new memory, and moving up frees up the corresponding space, so it is possible to manipulate the data in the stack with precision.
?? Examples are as follows:

2-2-2 New and delete

?? malloc and free are C++/C language standard library functions, and new/delete are operators of C + +. Note that one is a library function and one is an operator . ; Two what difference does it have? For library functions, when allocating heap memory, there is no concern for what the object is, only how much space is allocated, and the operator says that at allocation time the memory size is related to the class object, and the constructor of the class is called back when allocating memory.
?? They are used to apply dynamic memory and free memory. Since new is used to request memory, and the constructor can have parameters, the class type followed by new can also have parameters, in the following format:

newnew 类名[元素个数];

?? We find that we can apply an array of class objects, but it is important to note that when allocating an array of class objects from the heap, only the default constructor with no parameters can be called, and the parameter constructor cannot be called, and once the class does not have a default constructor, the class array cannot be assigned
?? As I said earlier, the memory space requested in the heap needs to be recycled manually, so using Delete to free up space calls the class's destructor. The format is as follows:

delete 变量名;     或   delete[] 变量名;变量名=null             变量名=null
Third, copy constructor function

?? A copy constructor is a special constructor whose formal parameter is a reference to an object of this class. The essence is to use one object to construct another object, or to initialize a new constructed object with another object value, in the following format:

class 类名{    public 类名(形参)          //构造函数    public 类名(类名 &对象名)   //拷贝构造函数}//拷贝构造函数的实现类名::类名(类名 &对象名){    函数体}

?? To give an example:

?? From the above example we find an interesting phenomenon: in the copy constructor we directly access the private members of the Class (PT.M_MX), other cases are unable to use the "." To access the
?? Copy constructors have the following characteristics:

 - 如果程序中没有为类声明一个拷贝构造函数,则编译器自己生成一个默认的拷贝构造函数 - 这个默认的拷贝构造函数执行功能是,把初始值对象中的每个数据成员值,都复制到新建立的对象中 - 在默认拷贝构造函数中,拷贝的策略是逐个成员依次拷贝

?? Because the copy constructor is passing in the object of this class, there is a problem.
?? When the constructor of a class allocates a resource on the heap, it is common to assign a value to the string, while the copy constructor is a copy of the resource, and if it is a simple copy, it causes two objects to have a resource at the same time, and when one object frees the resource, the other object becomes problematic when it is reused.

?? How can we solve this problem? Obviously the copy constructor cannot simply copy the resource, you need to write the copy constructor manually, and you cannot use the default copy constructor. A copy of the resource is required when the resource is copied, so that two objects point to different resources. This is the difference between a shallow copy and a deep copy.
?? Copy constructors are often used in the following

 - 当用类的一个对象去初始化该类的另一个对象时 - 若函数的形参是类的对象,调用函数时,实参赋值给形参,系统自动调用拷贝构造函数 - 当函数返回值是类的对象时,系统自动调用拷贝构造函数。

Iv. combination of Classes 4-1 what is a combination of classes

?? What is a combination of classes, simply speaking, the combination of classes is that the member data of a class is the object of another class, so that a more complex abstraction can be achieved on the basis of an existing abstraction.

Constructors for class 4-2 combinations

?? When our classes are combined, how do we initialize our classes? In general, it is not only the initial assignment of the type members in this class, but also the initial session of the object members. The declaration format is as follows:

类名::类名(对象成员所需的形参,本类成员形参):对象1(参数),对象2(参数){    本类初始化}

?? Examples are as follows:

?? When a class is combined, a new problem is encountered, and we know that each class has constructors and destructors, and when the class is combined, what is the order of the constructors and destructors?

 1. 构造函数的调用顺序      1. 调用内嵌对象的构造函数(按照内嵌时的声明顺序,先声明者先构造)      2. 调用本类构造函数 2. 析构函数的调用顺序     1. 调用本类析构函数     2. 调用内嵌对象的析构函数(按照内嵌时的声明顺序,先声明的先析构)

?? It is necessary to note that if you call the default constructor, the initialization of inline objects will also call the default constructor

V. Inheritance 5-1 inheritance and derivation

?? Since it is object-oriented and our display world is an object of the world, then we should also describe the relationship between real-world objects, such as inheritance, in order to describe the relationship between such classes, C + + also introduced the concept of inheritance
?? Inheritance is an important mechanism in C + +, which automatically provides operations and data structures from another class for a class, which allows us to define new classes only by defining components that have no existing classes in the new class. Inheritance is for the reuse and expansion of code
?? The general definition format for inheritance is as follows:

class 派生类:public 父类{    类的实现}

?? Since members in a class have different access rights, and class inheritance also has different inheritance methods (general class inheritance is divided into public inheritance, protection inheritance, private inheritance), then the class inherits, should also have different access permissions, different derivation and class members access to the following:

5-2 constructors and destructors for inheritance

?? Now that the members of the base class can be inherited, what about the special functions of the base class?
?? The constructor of a base class is not inherited, and derived classes are constructors that require their own life. However, at the time of the constructor, only the new members in this class need to be initialized, initialization of the inherited base class member, and the constructor of the base class is automatically called to complete.
?? The constructor of a derived class is as follows:

派生类名::派生类名(基类所需的形参,本类所需的形参):基类名(参数表){    本类成员初始化}

?? Examples are as follows:

?? Once you get involved in multiple categories, you must describe the order in which each class is called. In the case of inheritance, the constructor is called in the following order:

 - 调用基类的构造函数,调用顺序是按照他们被继承时的声明顺序(从左到右) - 调用成员对象的构造函数,调用顺序按照他们在类中声明的顺序 - 派生类的构造函数

?? Examples are as follows:

?? As with constructors, destructors cannot be inherited, and derived classes declare themselves in the same way as destructors for generic classes. It is important to note that there is no need to display a destructor for the call base class, which is automatically called implicitly, while the destructor is called in the reverse order of the constructor function.
?? Examples are as follows:

5-3 overriding the parent class method

?? The method defined by the general parent class can only manipulate members of the parent class, and when the subclass inherits, the method that calls the parent class is only allowed to inherit from the members of the parent class, and when the subclass wants to do the same, the method that calls the parent class is no longer able to complete, and the child class is required to override the parent class.
?? The runtime compiler invokes a method of the parent class or subclass according to our invocation situation. Examples are as follows:

Vi. polymorphism and virtual function 6-1 what is polymorphic

?? In reality, we often need to implement a function, that is, for the same function, when different objects go to run, will get different results, so it is very convenient for our program to write.
?? In order to realize this function, we need to adopt an important mechanism of C + +, polymorphism. The so-called polymorphism is that emitting the same message is accepted by different types of objects can lead to completely different behavior.
?? The realization of polymorphism relies on a technique of dynamic binding. What is binding? Bindings are procedures that the program itself associates with each other to determine the relationship between the action calls in the program and the execution of the operation code.
?? So there are two kinds of bindings, static binding and dynamic binding. Static bindings, also known as static binders, occur during the compilation phase, where dynamic binding is also called a dynamic union, which occurs during the execution of a program and determines which functions need to be called when the program is run .

6-2 Virtual functions

?? To prove that a function is polymorphic, we use the keyword virtual keyword to mark it, using the function of the token for our program virtual function. The virtual function is generally declared as follows:

virtual 返回值 函数名(参数列表)

?? For virtual functions we have two points to explain:

 1. virtual 只能用来说明类声明中的原型,不能用在函数的实现时 2. 基类中声明的虚函数,不管派生类是否声明吗,同原型函数都自动转换为虚函数

?? Examples are as follows:

?? How does a virtual function be implemented? The realization of the general virtual function is realized by a virtual function table , which is referred to as v-table. Virtual function table is mainly a virtual function Address table of a class , when using the parent class pointer to manipulate a subclass, the virtual function table is a map, to indicate the actual function should be called

?? What needs to be stated is:
1. The compiler holds a pointer to the virtual function table at the beginning of the object instance, and the virtual function table is obtained through the object's address, and the function pointer is traversed to invoke the corresponding function
2. virtual functions are placed in the table in their declaration order, and the parent virtual function is placed in front of the subclass virtual function
?? As I said before, the compiler does not compile dynamically unless the function is decorated with virtual, or the compiler does not know whether to post-compile. It can be said that the essence of virtual function is overwrite not overload declaration

?? According to the characteristics of virtual function, there are several points to be explained:

 1. 只有类成员函数才能说明为虚函数。虚函数仅适用于继承关系的类对象 2. 静态成员函数不能使虚函数,因为静态成员函数不受限于某个对象 3. 内联函数、构造函数不能使虚函数 4. 析构函数可以使虚函数,通常也就是虚函数
6-3 pure virtual function and abstract class

?? On the basis of virtual function We also have a virtual function called pure virtual function, that is, when the base class is not specifically implemented by a member function, left to the derived class to implement, equivalent to the subclass reserved a location for the derived class to implement.
?? Pure virtual functions are generally defined as follows:

Vitural 类型 函数名(参数表)=0

?? It can be found that the virtual function equals 0 is a pure virtual function. Classes that contain pure virtual functions are abstract classes.
?? Abstract classes are declared for abstraction and design purposes , and the related data and behaviors are organized in an inheritance hierarchy to ensure that derived classes have the required behavior. For a function that cannot be implemented temporarily, it can be declared as pure virtual function, which is left to the derived class to implement.
?? For abstract classes, you must specify

 1. 抽象类只能作为基类来使用 2. 不能声明抽象类的对象,哪怕是实现了部分纯虚函数的类

Hereby DECLARE:
?? This article for the original article, Welcome to love this article of the people to discuss, if there is insufficient affirmation everyone put forward. Thank you so much!!! At the same time, if reproduced please declare the source, thank you!!!

C + + classes and objects in a detailed

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.