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

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};
};

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

猜你喜欢

转载自blog.csdn.net/paradox_1_0/article/details/105982217