21 - 对象的构造顺序

---- 整理自狄泰软件唐佐林老师课程

1. 对象的构造顺序

  • C++ 中的类可以定义多个对象,那么对象构造的顺序是怎样的?

2.1 对于局部对象

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

2.1.1 下面程序中的对象构造顺序是什么?

在这里插入图片描述

2.1.2 实例分析:局部对象的构造顺序

#include <stdio.h>

class Test
{
private:
	int mi;
public:
	Test(int i) {
		mi = i;
		printf("Test::Test(int i): %d\n", mi);
	}
	Test(const Test& t) {
		mi = t.mi;
		printf("Test(const Test& t): %d\n", mi);
	}
};

int main()
{
	int i = 0;
    Test a1 = i; // 0
        
    while( i < 3 ) {
        Test a2 = ++i; // 1 2 3
    }
        
    if( i < 4 ) {
        Test a = a1; // 0
    } else {
        Test a(100);
    }

    return 0;
}

在这里插入图片描述

#include <stdio.h>

class Test
{
private:
	int mi;
public:
	Test(int i) {
		mi = i;
		printf("Test::Test(int i): %d\n", mi);
	}
	Test(const Test& t) {
		mi = t.mi;
		printf("Test(const Test& t): %d\n", mi);
	}
};

int main()
{
	int i = 0;
    Test a1 = i; // 0
        
    while( i < 3 ) {
        Test a2 = ++i; // 1 2 3
    }

	goto end;
	
    if( i < 4 ) {
        Test a = a1; // 0
    } else {
        Test a(100);
    }

end:
    return 0;
}

在这里插入图片描述

  • 不同的编译器可能结果不一样:g++
#include <stdio.h>

class Test
{
private:
	int mi;
public:
	Test(int i) {
		mi = i;
		printf("Test::Test(int i): %d\n", mi);
	}
	Test(const Test& t) {
		mi = t.mi;
		printf("Test(const Test& t): %d\n", mi);
	}
	int getMi() {
		return mi;
	}
};

int main()
{
	int i = 0;
    Test a1 = i; // 0
        
    while( i < 3 ) {
        Test a2 = ++i; // 1 2 3
    }

	goto end;
	
	Test a(100);

end:
	printf("a.mi: %d\n", a.getMi());

    return 0;
}

在这里插入图片描述

2.2 对于堆对象

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

2.2.1 下面程序中的对象构造顺序是什么?

在这里插入图片描述

2.2.2 实例分析:堆对象的构造顺序

#include <stdio.h>

class Test
{
private:
	int mi;
public:
	Test(int i) {
		mi = i;
		printf("Test::Test(int i): %d\n", mi);
	}
	Test(const Test& t) {
		mi = t.mi;
		printf("Test(const Test& t): %d\n", mi);
	}
	int getMi() {
		return mi;
	}
};

int main()
{
	int i = 0;
    Test* a1 = new Test(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;
}

在这里插入图片描述

2.3 对于全局对象

  • 全局对象的构造顺序不确定的
  • 不同的编译器使用不同的规则确定构造顺序
  • 实例分析:全局对象的构造顺序:
#include "test.h"

Test t1("t1");
#include "test.h"

Test t2("t2");
#include "test.h"

Test t3("t3");
#include "test.h"

Test t4("t4");
#include "test.h"

Test t5("t5");
#include "test.h"

Test t6("t6");
Test t7("t7");

int main()
{
	Test t8("t8");
   
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uuxiang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值