派生类的构造函数

由于派生类包含基类的原因,我们在创建一个派生类的时候,系统会先创建一个基类。需要注意的是,派生类会吸纳基类的全部成员,但并不包括构造函数及后面讲的析构函数,那么就意味着创建派生类在调用自己的构造函数之前,会先调用基类的构造函数。

#include <iostream>
using namespace std;

class Base{
public:
	Base(){
		cout << "This is Base constructor" << endl;
	}
	~Base(){
		cout << "THis is Base discontructor" << endl;
	}
	Base(int n): num(n){}

	void print(){
		cout << "Hello Base class: " << num << endl;
	}

private:
	int num = 1;
};

class Derived : public Base{
public:
	Derived(){
		cout << "This is Derived constructor" << endl;
	}
	~Derived(){
		cout << "THis is Derived disconstructor" << endl;
	}
	//基类如果有带参构造函数,那么派生类通过基类的构造函数
	//来初始化它的基类部分
	//首先初始化基类部分,然后再依次初始化它自己的部分
	Derived(int n): Base(n), code(n){}

	void greet(){
		cout << "Hello, Derived class: " << code << endl;
	}

private:
	int code = 2;
};

int main(){
	Derived A, B(10);
	A.print();
	A.greet();
	B.print();
	B.greet();
	return 0;
}

运行结果:

 

转载于:https://www.cnblogs.com/mocuishle/p/8322481.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值