c++ 构造函数、赋值构造函数、拷贝构造函数 例子备忘

本文通过具体的C++代码示例,详细介绍了类的定义、构造函数、析构函数、复制构造函数、赋值运算符重载以及派生类的实现。特别关注了资源管理,如动态内存分配和释放,以及如何正确地进行深拷贝。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


class classA
{
public:
	int a;
	int *b;

	classA():a(2),b() {
		cout << "classA()" << endl;
		b = new int[2];
	};
	~classA() {
		cout << "~classA()" << endl; delete[] b; };

	classA(const classA& info)
	{
		cout << "classA(const classA& info)" << endl;
		a = info.a;
		b = new int[2];
		b[0] = info.b[0];
		b[1] = info.b[1];
	}
	classA& operator = (const classA& info)
	{
		cout << "classA& operator = (const classA& info)" << endl;
		a = info.a;
		b[0] = info.b[0];
		b[1] = info.b[1];
		return *this;
	}
};
class classB :public classA
{
public :
	int c;
	int *d;
	classB() :c(3) {
		cout << "classB()" << endl;
		d = new int[2];
	};
	~classB() {
		cout << "~classB()" << endl; 
		delete[] d; };

	classB(const classB& info):classA(info)
	{
		cout << "classB(const classB& info):classA(info)" << endl;
		c = info.c;
		d = new int[2];
		d[0] = info.d[0];
		d[1] = info.d[1];
	}
	classB& operator = (const classB& info) 
	{
		if (this == &info)
		{
		    return *this;
		}
		classA::operator=(info);
		cout << "classB& operator = (const classB& info) " << endl;
		c = info.c;
		d[0] = info.d[0];
		d[1] = info.d[1];
		return *this;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值