派生类的构造函数表示

  1. 派生类对象单元中含有基类数据——基类数据可以在基类中初始化
    i:派生类构造函数可通过调用基类构造函数完成派生类对象中基类数据成员的初始化
    ii:派生类的构造函数体只表示派生类中数据成员的初始化
  2. 表示:派生类名(总形参):基类名(实参)
    {
    //派生类构造函数体
    };
#include<iostream>
using namespace std;
class Base{
	private:
		int x,y;
	public:
		Base(){
			x=0;
			y=0;
		}
		Base(int x,int y){
			this->x=x;
			this->y=y;
		}
		void Print()
		{
			cout<<x<<" "<<y<<endl; 
		}
};
class Derived:public Base{
	private:
		int z;
	public:
		Derived()
		{
			z=0;
		}
		Derived(int i):Base(i+3,i-1)
		{
			z=i;
		}
		void Print()
		{
			Base::Print();
			cout<<z<<endl;
		}
};
int main()
{
	Derived objD(3);
	objD.Print();
	return 0;
}
  1. 派生类构造函数的调用顺序:①调用基类构造
    ②执行派生类构造函数体
  2. 释放派生类对象时,要调用析构函数,析构函数的调用严格与构造函数相反
#include<iostream>
using namespace std;
class Base{
	private:
		int x,y;
	public:
		Base(){
			x=0;
			y=0;
			cout<<"Base Cons!"<<endl; 
		}
		Base(int x,int y){
			this->x=x;
			this->y=y;
			cout<<"Base Cons!"<<endl; 
		}
		void Print()
		{
			cout<<"x="<<x<<endl;
			cout<<"y="<<y<<endl; 
		}
		~Base()
		{
			cout<<"Base Des!"<<endl;
		}
};
class Derived:public Base{
	private:
		int z;
	public:
		Derived()
		{
			z=0;
			cout<<"Derived Cons!"<<endl;
		}
		Derived(int i):Base(i+3,i-1)
		{
			z=i;
			cout<<"Derived Cons!"<<endl;
		}
		void Print()
		{
			Base::Print();
			cout<<"z="<<z<<endl;
		}
		~Derived()
		{
			cout<<"Derived Des!"<<endl;
		}
};
int main()
{
	/*Derived objD(3);
	objD.Print();*/
	Derived *p=new Derived(3);
	p->Print();
	delete p;
	return 0;
}
  1. 含有子对象的派生类的构造函数表示:
    派生类名(总形参):基类名(实参),子对象1(实参),子对象2(实参)…
    {
    //派生类构造函数体
    };
  2. 派生类构造函数的调用顺序:
    调用基类构造函数—》调用子对象构造函数—》执行派生类构造函数体
  3. 若含有多个子对象,按子对象定义顺序调用构造函数
#include<iostream>
using namespace std;
class Myclass{
	public:
		Myclass()
		{
			cout<<"Myclass cons!"<<endl;
		}
		~Myclass()
		{
			cout<<"Myclass Des!"<<endl;
		}
};
class Yourclass{
	public:
		Yourclass()
		{
			cout<<"Yourclass cons!"<<endl;
		}
		~Yourclass()
		{
			cout<<"Yourclass Des!"<<endl;
		}
};
class Base{
	private:
		Myclass my;
	public:
		Base()
		{
			cout<<"Base cons!"<<endl;
		}
		~Base()
		{
			cout<<"Base Des!"<<endl;
		}	
};
class Derived:public Base{
	private:
		Myclass objMy;
		Yourclass objYour;
		Base objBase;
	public:
		Derived()
		{
			cout<<"Derived Cons!"<<endl;
		}
		~Derived()
		{
			cout<<"Derived Des!"<<endl;
		}
};
int main()
{
	Derived *p=new Derived();
	delete p;
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值