问题 1:C++ 中的类可以定义多个对象,那么对象构造的顺序是怎样的?问题 2:对象构造顺序会带来什么影响呢?对象构造往往与构造函数相关联,构造函数体有可能是非常复杂的程序逻辑组成,不同类的构造函数中程序逻辑可能是相互依赖的。当相互依赖发生时,对象的构造顺序就变得尤为重要。对象的构造顺序 一对于局部对象(包含静态局部对象)当程序执行流到达对象的定义语句时进行构造下面程序中的对象构造顺序是什么?void code(){ int i = 0; Test a1 = i; while( i < 3) Test a2 = ++i; if( i < 4 ) { Test a = a1; } else { Test a(100); }}实例分析: 局部对象的构造顺序test_1.cpp#include <stdio.h>class Test{private: int mi;public: Test(int i) { mi = i; printf(“Test(int i) : %d\n”, mi); } Test(const Test& obj) { mi = obj.mi; printf(“const Test& obj : %d\n”, mi); }};int main(){ int i = 0; Test a1 = i; while( i < 3) Test a2 = ++i; if( i < 4 ) { Test a = a1; } else { Test a(100); } return 0;}输出:Test(int i) : 0Test(int i) : 1Test(int i) : 2Test(int i) : 3const Test& obj : 0结论:局部对象的构造顺序与程序的执行流相关error.cpp#include <stdio.h>class Test{private: int mi;public: Test(int i) { mi = i; printf(“Test(int i) : %d\n”, mi); } Test(const Test& obj) { mi = obj.mi; printf(“const Test& obj : %d\n”, mi); } int getMi() { return mi; }};int main(){ int i = 0; Test a1 = i; while( i < 3) Test a2 = ++i; goto End; // 注意这里! Test a(100);End: printf(“a.mi = %d\n”, a.getMi()); return 0;}g++ 输出:test.cpp:30: error: jump to label ‘End’test.cpp:28: error: from heretest.cpp:29: error: crosses initialization of ‘Test a’vc2010 编译输出:error.cpp(34) : warning C4533: “goto a”跳过了“End”的初始化操作error.cpp(33) : 参见“a”的声明error.cpp(34) : 参见“End”的声明vc2010 运行输出:Test(int i) : 0Test(int i) : 1Test(int i) : 2Test(int i) : 3a.mi = 4076341发生了什么?程序的执行流被改变,意味着对象 a 的状态是没有被初始化的(构造函数没有被调用)。那么之后使用该对象的结果将是不确定的,可能导致严重的灾难!!所以当定义使用对象时,要对程序的执行流有清晰的认识。g++给出错误提示,不可以保证所有的编译器都有这样的实现,因为这不是C++的标准。VC2010未给出错误提示,仅给出警告。对象的构造顺序 二对于堆对象当程序执行流到达 new 语句时创建对象使用 new 创建对象将自动触发构造函数的调用下面程序中的对象构造顺序是什么?void code(){ int i = 0; Test* a1 = new Test(i); while( ++i < 10 ) if( i % 2 ) new Test(i); if( i < 4 ) new Test(a1); else new Test(100); return 0;}编程实验: 堆对象的构造顺序#include <stdio.h>class Test{private: int mi;public: Test(int i) { mi = i; printf(“Test(int i) : %d\n”, mi); } Test(const Test& obj) { mi = obj.mi; printf(“const Test& obj : %d\n”, mi); } int getMi() { return mi; }};// 这里在 new 之后没有 delete,仅为演示int main(){ int i = 0; Test a1 = new Test(i); while( ++i < 10 ) if( i % 2 ) new Test(i); if( i < 4 ) new Test(a1); else new Test(100); return 0;}输出:Test(int i) : 0Test(int i) : 1Test(int i) : 3Test(int i) : 5Test(int i) : 7Test(int i) : 9Test(int i) : 100结论:堆对象的构造顺序与程序的执行流相关。堆对象同样受到程序执行流的影响,具体可参考局部对象中的分析。对象的构造顺序 三对于全局对象对象的构造顺序是不确定的不同的编译器使用不同的规则确定构造顺序实例分析: 全局对象的构造顺序test.h#ifndef TEST_H#define TEST_H#include <stdio.h>class Test{public: Test(const char s) { printf("%s\n", s); }};#endift1.cpp#include “test.h"Test t1(“t1”);t2.cpp#include “test.h"Test t2(“t2”);t3.cpp#include “test.h"Test t3(“t3”);test.cpp#include “test.h"Test t4(“t4”);int main(){ Test t5(“t5”); return 0;}g++ 输出:t3t2t1t4t5vc2010 输出:t4t1t2t3t5警示: 尽量避开全局对象,尽量避开全局对象的相互依赖小结局部对象的构造顺序依赖于程序的执行流堆对象的构造顺序依赖于 new 的使用顺序全局对象的构造顺序是不确定的以上内容参考狄泰软件学院系列课程,请大家保护原创!