C++派生类的构造函数与析构函数

本文深入探讨C++中的构造函数与析构函数,包括无参与有参构造函数的使用,以及如何在继承与包含关系中正确初始化成员变量。通过具体的代码示例,展示了Parent、Child、B与A类的构造过程与析构顺序,帮助读者理解C++对象生命周期管理的核心概念。

存个代码

#include <bits/stdc++.h>
using namespace std;
class Parent {
protected:
	int pnum;
public:
	Parent(){
		pnum = 0;
		cout << "调用Parent的无参构造函数" << endl;
	}
	Parent(int pnum) {
		this->pnum = pnum;
		cout << "调用Parent的有参构造函数" << endl;
	}
	~Parent() {
		cout << "调用Parent的析构函数" << endl;
	}
	void show() {
		cout << pnum << endl;
	}
};
class Child : public Parent {
protected:
	int cnum;
public:
	Child() : Parent() {
		pnum = 0;
		cnum = 0;
		cout << "调用Child的无参构造函数" << endl;
	}
	Child(int pnum, int cnum) : Parent(pnum) {
		this->cnum = cnum;
		cout << "调用Child的有参构造函数" << endl;
	}
	~Child() {
		cout << "调用Child的析构函数" << endl;
	}
	void show() {
		cout << pnum << ' ' << cnum << endl;
	}
};
class B {
public:
	int bnum;
	B() {
		bnum = 0;
		cout << "调用B的无参构造函数" << endl;
	}
	B(int bnum) {
		this->bnum = bnum;
		cout << "调用B的有参构造函数" << endl;
	}
	~B() {
		cout << "调用B的析构函数" << endl;
	}
	void show() {
		cout << bnum << endl;
	}
};
class A : public Parent {
private:
	int anum;
	B b; // A类中定义了B类的对象 
public:
	A() : Parent(), b() {
		pnum = 0;
		b.bnum = 0;
		anum = 0;
		cout << "调用A的无参构造函数" << endl;
	}
	A(int pnum, int bnum, int anum) : Parent(pnum), b(bnum) {
		this->anum = anum;
		cout << "调用A的有参构造函数" << endl;
	}
	~A() {
		cout << "调用A的析构函数" << endl;
	}
	void show() {
		cout << pnum << ' ' << b.bnum << ' ' << anum << endl;
	}
};
int main() {
	Parent p1;
	Parent p2(5);
	p1.show();
	p2.show();
	
	cout << "****************" << endl;
	
	Child c1;
	Child c2(1, 2);
	c1.show();
	c2.show();
	
	cout << "****************" << endl;
	
	B b1;
	B b2(10);
	b1.show();
	b2.show();
	
	cout << "****************" << endl;
	
	A a1;
	A a2(5, 6, 7);
	a1.show();
	a2.show();
	return 0;
}

结果

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值