C++:继承中的构造函数和析构函数

C++:继承中的构造函数和析构函数

1、继承中构造函数和析构函数调用顺序

a、调用父类构造函数;

b、调用其他成员的构造函数;

c、调用子类构造函数;

d、析构调用顺序相反。

#include <iostream>
using namespace std;

class Base
{
public:
	Base()
	{
		cout<<"Base中的默认构造函数调用"<<endl;
	}
	~Base()
	{
		cout<<"Base中的析构函数调用"<<endl;
	}
};

class Other
{
public:
	Other()
	{
		cout<<"Other中的默认构造函数调用"<<endl;
	}

	~Other()
	{
		cout<<"Other中的析构函数调用"<<endl;
	}
};

class Son : Base
{
public:
	Son()
	{
		cout<<"Son中的默认构造函数调用"<<endl;
	}
	
	~Son()
	{
		cout<<"Son中的析构函数调用"<<endl;
	}
	
	Other o;
};

int main()
{
	Son s;
    return 0;
}

2、子类默认调用父类的默认构造函数。因此父类须提供默认构造函数,否则子类须利用初始化列表方法显式调用父类的其他构造函数

#include <iostream>
using namespace std;

// 该类中仅提供了有参构造函数,无默认构造函数
class Base
{
public:
    int m_A;
public:
	Base(int var)
	{
		this->m_A = var;
		cout<<"Base中的有参构造函数调用"<<endl;
	}
};

class Son : public Base
{
public:
    // 继承的父类Base中无默认构造函数,须利用初始化列表方法,显式调用父类其他构造函数。
	explicit Son02(int a = 0): Base(a)
	{
		cout<<"Son中的有参构造函数调用"<<endl;
	}
};

void test02(){
	Son s;
	cout<<s.m_A<<endl;
}

3、父类中的构造函数(默认、有参、拷贝)、析构及赋值运算符函数不会被子类继承

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值