C ++ constructs, analyzes the structure sequence (static objects), and constructs static objects.
Test code:
# Include <iostream> # include <cstdlib> using namespace std; class A {public: A () {cout <"A-constructor" <endl ;}~ A () {cout <"A-destructor" <endl ;}}; class B: public A {public: B () {cout <"B-constructor" <endl ;}~ B () {cout <"B-destructor" <endl ;}}; class C {public: C () {cout <"C-constructor" <endl ;}~ C () {cout <"c-destructor" <endl ;}}; class E {public: E () {cout <"e-constructor" <endl ;}~ E () {cout <"E-destructor" <endl ;}}; class D: public E {public: D () {cout <"D-constructor" <endl ;}~ D () {cout <"D-destructor" <endl;} private: C c; static B B ;}; B d: B; int main () {D d; cout <"Hello world! "<Endl; return 0 ;}
The running result is as follows:
Analysis: in a class, if other class members exist, they are constructed first. If the class object is static, the static object is constructed before all other objects, if this static object inherits A parent class, it should first construct the parent class and construct the derived class, so A-constructor; B-constructor; e-constructor (Constructor's parent class ); c-constructor; D-constructor;
The order of the analysis structure is opposite to that of the static function.
Test code: without static objects:
# Include <iostream> # include <cstdlib> using namespace std; class A {public: A () {cout <"A-constructor" <endl ;}~ A () {cout <"A-destructor" <endl ;}}; class B: public A {public: B () {cout <"B-constructor" <endl ;}~ B () {cout <"B-destructor" <endl ;}}; class C {public: C () {cout <"C-constructor" <endl ;}~ C () {cout <"c-destructor" <endl ;}}; class E {public: E () {cout <"e-constructor" <endl ;}~ E () {cout <"E-destructor" <endl ;}}; class D: public E {public: D () {cout <"D-constructor" <endl ;}~ D () {cout <"D-destructor" <endl;} private: C c; B B ;}; // B d: B; int main () {D d; cout <"Hello world! "<Endl; return 0 ;}
The result is as follows:
Without static objects, first construct your own parent class (if any), and then construct the members in the class, c-constructor; B-constructor (A is the parent class first constructor ), finally, the self-built constructor D-constructor is opposite to the constructor D-constructor;
Summary: Structure sequence:
1. Execute the destructor of the function body first.
2. Then, execute the analysis structure of all non-static objects in the opposite way according to the clear voice.
3. Execute your own parent destructor
4. If a static member object exists
Construction Order:
1. First, construct your own parent class. If there is a static member object, first construct the parent class of the static member object, then the static member object, and then the parent class.
2. Construction of other non-static member objects
3. self-built Constructors