21-对象的构造顺序
1、对于局部对象:
- 当程序执行流到达对象的定义语句时进行构造。
【范例代码】局部对象的构造顺序
#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("Test(const Test& obj): %d\n", mi);
}
};
int main(int argc, const char* argv[]) {
int i = 0;
Test a1 = i;
while (i < 3) {
Test a2 = ++i;
}
if (i < 4) {
Test a = a1;
} else {
Test a(100);
}
return 0;
}
2、对于堆对象:
- 当程序执行流到达new语句时创建对象
- 使用new创建对象将自动触发构造函数的调用
【范例代码】堆对象的构造顺序
#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("Test(const Test& obj): %d\n", mi);
}
int getMi() {
return mi;
}
};
int main(int argc, const char* argv[]) {
int i = 0;
Test* a1 = new Test(i); // Test(int i): 0
while (++i < 10)
if (i % 2)
new Test(i); // Test(int i): 1, 3, 5, 7, 9
if (i < 4)
new Test(*a1);
else
new Test(100); // Test(int i): 100
return 0;
}
3、对于全局对象:- 对象的构造顺序是不确定的
- 不同的编译器使用不同的规则确定构造顺序
【范例代码】全局对象的构造顺序
test.h文件:
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
class Test {
public:
Test(const char* s) {
printf("%s\n", s);
}
};
#endif
t1.cpp文件:
#include "test.h"
Test t1("t1");
t2.cpp文件:
#include "test.h"
Test t2("t2");
t3.cpp文件:
#include "test.h"
Test t3("t3");