Explanation of dynamic Establishment and release of objects in C++ and the difference between object Array and pointer Array
This article mainly explains "the dynamic establishment and release of objects in C++ and the difference between object array and pointer array". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "the dynamic establishment and release of objects in C++ and the difference between object arrays and pointer arrays".
Catalogue
Overview
Dynamic establishment and release of objects
Case
Object array vs pointer array
Object array
Pointer array
Overview
Through the dynamic establishment and release of objects, we can improve the utilization of memory space.
Dynamic establishment and release of objects
New operator: dynamically allocating memory
Delete operator: freeing memory
When we allocate memory dynamically with the new operator, a pointer to the new object is returned. We can access the object through this address. For example:
Int main () {Time * pt1 = new Time (8,8,8); pt1-> show_time (); delete pt1; / / release object return 0;}
Output result:
8:8:8
When we no longer need the object created by new, release it with the delete operator.
Case
Box class:
# ifndef PROJECT1_BOX_H#define PROJECT1_BOX_Hclass Box {public: / / member object double length; double width; double height; / / member function Box (); / No parameter construction Box (double h, double w, double l); / / parameter construction ~ Box (); / / destructor double volume () const; / / constant member function}; # endif / / PROJECT1_BOX_H
Box.cpp:
# include # include "Box.h" using namespace std;Box::Box (): height (- 1), width (- 1), length (- 1) {} Box::Box (double h, double w, double l): height (h), width (w), length (l) {cout