C++. 派生类的复制操作也必须处理它的基类成员的复制

本文深入解析C++中派生类构造函数、拷贝构造函数及赋值运算符的实现细节,强调在派生类含有非静态数据成员时,正确调用基类构造函数、拷贝构造函数及赋值运算符的重要性。

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

class Copy {
public:
	Copy(){}
	Copy(int c) : c_(c){}
private:
	int c_;
};

class Copytest : public Copy {
public:
	Copytest(){}
	Copytest(int a, int c) : a_(a), Copy(c) {

	}
	Copytest(const Copytest& c) : Copy(c) {
		a_ = c.a_;
	}
	Copytest& operator=(const Copytest& c) {
		
		// 把自身赋值给自身的情况, 其实这里也可以不用
		if (this == &c)
			return *this;

		Copy::operator=(c);
		a_ = c.a_;
		return *this;
	}
#if 0
	//默认生成
	Copytest();
	Copytest(const CopyTest& c);
	Copytest& operator=(const Copytest& c);
	// 析构函数
	~Copytest();
	// 在c++11之后:移动构造函数和移动赋值运算符
	CopyTest(Copytest&& c);
	CopyTest& operator=(Copytest&& c);

#endif
private:
	int a_{10};
};

所以在派生类中(基类有非静态数据成员),派生类构造函数需要调用基类构造函数、派生类拷贝构造函数需要调用基类拷贝构造函数、派生类赋值运算符需要调用基类赋值运算符。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值