1.对象的构造顺序一

—-对于局部对象

当程序执行流执行到对象定义的语句时进行构造

  1. #include<stdio.h>
  2. class Test
  3. {
  4. private:
  5. int mi;
  6. public:
  7. Test(int i)
  8. {
  9. printf("Test(int i):i = %d\n",i);
  10. mi = i;
  11. }
  12. Test(const Test& obj)
  13. {
  14. printf("Test(const Test& obj):i = %d\n",obj.mi);
  15. mi = obj.mi;
  16. }
  17. };
  18. int main()
  19. {
  20. int i = 0;
  21. Test a1 =i;
  22. while( i < 3)
  23. {
  24. Test a2 = ++i; //i = 1,2,3
  25. }
  26. if( i < 4)
  27. Test a3 = a1; //Test(const Test& obj):i =0
  28. else
  29. Test a4(100);
  30. //printf("%d\n",a4.getmi()); //在vs中会被调用,产生灾难
  31. return 0;
  32. }
  33. //按顺序构造
  34. Test(int i):i = 0
  35. Test(int i):i = 1
  36. Test(int i):i = 2
  37. Test(int i):i = 3
  38. Test(const Test& obj):i = 0

—-对于堆对象

—-当程序执行流到达new语句时创建对象
—-适应new对象创建对象将自动触发构造函数的调用

  1. #include<stdio.h>
  2. class Test
  3. {
  4. private:
  5. int mi;
  6. public:
  7. Test(int i)
  8. {
  9. printf("Test(int i):i = %d\n",i);
  10. mi = i;
  11. }
  12. Test(const Test& obj)
  13. {
  14. printf("Test(const Test& obj):i = %d\n",obj.mi);
  15. mi = obj.mi;
  16. }
  17. };
  18. int main()
  19. {
  20. int i = 0;
  21. Test* a1 = new Test(i); //Test(int i):i = 0
  22. while( ++i < 10)
  23. {
  24. if( i % 2 )
  25. new Test(i); //Test(int i):i = 1,3,5,7,9
  26. }
  27. if( i < 4)
  28. new Test(*a1);
  29. else
  30. new Test(100); //Test(int i):i = 100
  31. return 0;
  32. }
  33. 结果:
  34. Test(int i):i = 0
  35. Test(int i):i = 1
  36. Test(int i):i = 3
  37. Test(int i):i = 5
  38. Test(int i):i = 7
  39. Test(int i):i = 9
  40. Test(int i):i = 100

—-对于全局对象

全局对象的构造顺序是不确定的!!!
不同的编译器使用不同的规则确定构造顺序

  1. //t1.cpp
  2. #include "test.h"
  3. Test t1("t1");
  4. //t2.cpp
  5. #include "test.h"
  6. Test t2("t1");
  7. //t3.cpp
  8. #include "test.h"
  9. Test t3("t1");
  10. //test.h
  11. #ifndef _TEST_H_
  12. #define _TEST_H_
  13. #include <stdio.h>
  14. class Test
  15. {
  16. public:
  17. Test(const char* s)
  18. {
  19. printf("%s\n", s);
  20. }
  21. };
  22. #endif
  23. //main.cpp
  24. #include "test.h"
  25. Test t4("t4");
  26. int main()
  27. {
  28. Test t5("t5");
  29. }
  30. //在linux和vs中的构造顺序不一样

小结:

1.局部对象的构造顺序依赖于程序的执行流
2.堆对象的构造顺序依赖于new的使用顺序
3.全局对象的构造顺序不确定