ObjDef.h /* * * Date: 2019.09.07 * */ #ifndef _H_H_OBJ_DEF_H_H_ #define _H_H_OBJ_DEF_H_H_ #include iostream class ObjA{ public : ObjA() { std::cout " Construct ObjA " std::endl; } ~ObjA() { std::cout " Destruct ObjA " std::endl; }}; class O
ObjDef.h
/* * * Date: 2019.09.07 * */ #ifndef _H_H_OBJ_DEF_H_H_ #define _H_H_OBJ_DEF_H_H_ #include <iostream> class ObjA { public: ObjA() { std::cout << "Construct ObjA" << std::endl; } ~ObjA() { std::cout << "Destruct ObjA" << std::endl; } }; class ObjB { public: ObjB() { std::cout << "Construct ObjB" << std::endl; } ~ObjB() { std::cout << "Destruct ObjB" << std::endl; } }; class ObjC { public: ObjC() { std::cout << "Construct ObjC" << std::endl; } ~ObjC() { std::cout << "Destruct ObjC" << std::endl; } }; #endif
main.cpp
/* * * Date: 2019.09.07 * */ #include <iostream> #include "ObjDef.h" ObjA a; ObjB b; ObjC c; int main() { std::cout << "Hello World" << std::endl; return 0; }
执行结果
结论:
全局对象初始化的顺序正好与析构的顺序相反。
可以按栈的数据结构进行理解,先进后出,先调用初始化的,后调用析构。
局部对象初始化与析构的顺序,与全局对象一致。