派生类的构造函数及其对象的初始化

本文探讨了C++中派生类构造函数的工作原理和对象初始化的顺序。在构造过程中,基类的构造函数按声明顺序初始化,而成员初始化列表中的顺序可能与其执行顺序不同。在析构时,系统则按照构造的逆序进行。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;

class Base1
{
	int d1;
public:
	Base1(int i)
	{
		d1 = i;
		cout<<"constructing Base1: "<<d1<<endl;
	}
};

class Base2
{
	int d2;
public:
	Base2(int j)
	{
		d2 = j;
		cout<<"constructing Base2: "<<d2<<endl;
	}
};

class Base3
{
	int d3;
public:
	Base3(int k=0)
	{
		d3 = k;
		cout<<"constructing Base3: "<<d3<<endl;
	}
};

class Derived:public Base3, public Base1, public Base2
{
	int d4;
	Base1 memberOBJ1;
	Base3 memberOBJ3;
	Base2 memberOBJ2;
public:
	Derived(int a, int b, int c, int d, int e):memberOBJ2(d), memberOBJ3(b), memberOBJ1(c), Base2(a), Base1(b)
	{
		d4 = e;
		cout<<"constructing Derived: "<<d4<<endl;
	}
};

void main()
{
	Derived obj(1,2,3,4,5);
	while(1);
}
派生类Derived由三个基类Base3,Base1和Base
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值