10-C++ object-oriented (constructor, destructor)

Object's memory:

        Object memory can exist in 3 places

                1. Global area (data segment): global variables

                2. Stack space: local variables in the function

                3. Heap space: dynamically apply for memory (malloc, new, etc.)

//全局区
Person g_person;

int main(){
    //栈空间
    Person person;

    //堆空间
    Person *p=new Person;
    return 0;

    //这不是申请对象,这是函数申明
	Person person();
}

Constructor

        Constructor (also called constructor), which is automatically called when the object is created, is generally used to complete the initialization of the object

        The function name has the same name as the class, has no return value (void cannot be written), can have parameters, can be overloaded, and can have multiple constructors

        Once the constructor is defined, the object must be initialized with one of the custom constructors

        Objects allocated by malloc do not call constructors

        If the constructor is defined, except for the global area, the member variables of other memory spaces will not be initialized by default, and developers need to initialize manually

Destructor

        The destructor (also called the destructor) is automatically called when the object is destroyed, and is generally used to clean up the object

        The function name starts with "~", has the same name as the class, has no return value (void cannot be written), has no parameters, cannot be overloaded, and has only one destructor

        The constructor will not be called when the object allocated by malloc is free

        Constructors and destructors must be declared public in order to be used normally by the outside world

Guess you like

Origin blog.csdn.net/qq_56728342/article/details/129661556