构造函数与析构函数

/*构造函数--组合和继承*/
/*一般来说子类不继承父类的构造函数*/ 
#include <iostream>
using namespace std;

class Base1{
	public:
		Base1(int i){  //基类Base1,构造函数有参 
			cout << "Constructing Base1 " << i << endl; 
		}
};

class Base2{
	public:
		Base2(int j){  //基类Base2,构造函数有参 
			cout << "Constructing Base2 " << j << endl; 
		}
};

class Base3{
	public:
		Base3(){  //基类Base3,构造函数无参 
			cout << "Constructing Base3* " << endl; 
		}
}; 

class Derived:public Base2, public Base1, public Base3{ //注意基类名继承的顺序 
	public:
		Derived(int a, int b, int c, int d):Base1(a), member2(d), member1(c), Base2(b){}
	private:
		Base1 member1;
		Base2 member2;
		Base3 member3;
}; 
int main(){
	Derived obj(1, 2, 3, 4);//执行时候先初始化基类的构造函数,执行顺序按照派生类公有继承基类的顺序 
	return 0;               //所以先执行Base2(2), 再执行Base1(1),最后执行无参的Base3; 
}                           //再者初始化私有成员类的对象,按照member1(3), member2(4),member3的顺序 

/*构造函数的析构函数--和构造函数一样不被子类继承*/ 
#include <iostream>
using namespace std;

class Base1{
	public:
		Base1(int i){  //基类Base1,构造函数有参 
			cout << "Constructing Base1 " << i << endl; 
		}
		~Base1(){
			cout << "Destructing Base1" << endl; 
		} 
};

class Base2{
	public:
		Base2(int j){  //基类Base2,构造函数有参 
			cout << "Constructing Base2 " << j << endl; 
		}
		~Base2(){
			cout << "Destructing Base2" << endl;
		} 
};

class Base3{
	public:
		Base3(){  //基类Base3,构造函数无参 
			cout << "Constructing Base3* " << endl; 
		}
		~Base3(){
			cout << "Destructing Base3" << endl;
		} 
}; 

class Derived:public Base2, public Base1, public Base3{ //注意基类名继承的顺序 
	public:
		Derived(int a, int b, int c, int d):Base1(a), member2(d), member1(c), Base2(b){}
	private:
		Base1 member1; //析构函数首先在结束时析构本类的对象成员,但执行顺序和构造函数相反,从最后的member3~member1这个顺序执行 
		Base2 member2;//然后再析构基类的对象,析构的顺序按照公有继承顺序的反方向,先Base3再Base1最后Base2 
		Base3 member3;
}; 
int main(){
	Derived obj(1, 2, 3, 4);//执行时候先初始化基类的构造函数,执行顺序按照派生类公有继承基类的顺序 
	return 0;               //所以先执行Base2(2), 再执行Base1(1),最后执行无参的Base3; 
}                           //再者初始化私有成员类的对象,按照member1(3), member2(4),member3的顺序 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

金州饿霸

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

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

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

打赏作者

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

抵扣说明:

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

余额充值