派生类构造函数与析构函数的构造规则

1.派生类的构造函数可以不显示式的写出基类的构造函数。例如:

Third()
{e=0;}

此时,系统自动调用基类的无参构造函数(没有,则为默认的构造函数)。也可显示式的指出调用基类的哪一个构造函数。例如:

Third(int x,int y,int z):Second(x,y)
{
e=z;
}

2.要调用的基类构造函数的参数可在派生类的构造函数中明确给出。例如:

Third(int x,int y,int z):Second(x,y)
{
e=z;
}

也可不给出:

Second():First(1,1)
{
c=0;
d=0;
}

还可以对派生类构造函数的参数进行一些交换,再传递给要调用的基类的构造函数,例如:

Second(int x,int y):First(x+1,y+1)
{
c=x;
d=y;
}

一个完整的例子如下:

#include<iostream>
using namespace std;
class First{
public:
	First()
	{
		a=0;
		b=0;
	}
	First(int x,int y)
	{a=x;
	 b=y;
	}
	~First()
	{
		cout<<"destructing First"<<endl;
	}
	void show()
	{
     cout<<"\n a="<<a<<"\n b="<<b<<endl;
	}
private:
	int a;
	int b;
};
class Second:public First{
public:
	Second():First(1,1)
	{
		c=0;
		d=0;
	}
	Second(int x,int y):First(x+1,y+1)
	{
		c=x;
		d=y;
	}
	Second(int x,int y,int m,int n):First(m,n)
	{
		c=x;
		d=y;
	}
	~Second()
	{
		cout<<"destructing Second"<<endl;
	}
	void show()
	{
		First::show();
		cout<<"c="<<c<<"d="<<d<<endl;
	}
private:
	int c,d;

};
class Third:public Second{
public:
	Third()
	{e=0;}
	Third(int x,int y,int z):Second(x,y)
	{
         e=z;
	}
	Third(int x,int y,int z,int m,int n):Second(x,y,m,n)
	{
		e=z;
	}
	~Third()
	{
		cout<<"destructing Third"<<endl;
	}
	void show()
	{
		Second::show();
		cout<<"e="<<e<<endl;
	}
private:
	int e;
};
int main()
{
	First f;
	f.show();
	cout<<"======================"<<endl;
	Second d1;
	d1.show();
	cout<<"======================"<<endl;
	Second d2(10,20,30,40);
    d2.show();
	cout<<"====================="<<endl;
	Second d3(12,13);
	d3.show();
	cout<<"======================="<<endl;
	Third t;
	t.show();
	cout<<"======================"<<endl;
	Third t1(14,15,16);
	t1.show();
	cout<<"======================="<<endl;
	Third t2(50,60,70,80,90);
	t2.show();
	return 0;

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值