如何为包含指向(抽象)基类的指针的类定义拷贝构造函数或复制操作符

#include <iostream>
using namespace std;

// 如何为包含指向(抽象)基类的指针的类定义拷贝构造函数或复制操作符
class Shape
{
public:
	Shape()
	{
		cout << "Shape::Shape()" << endl;
	}
	virtual ~Shape()
	{
		cout << "Shape::~Shape()" << endl;
	}
	virtual Shape* clone() const = 0;
};

class Circle : public Shape
{
public:
	Circle()
	{
		cout << "Circle::Circle()" << endl;
	}
	~Circle()
	{
		cout << "Circle::~Circle()" << endl;
	}
	virtual Shape* clone() const
	{
		return new Circle(*this);
	}
};

class Square : public Shape
{
public:
	Square()
	{
		cout << "Square::Square()" << endl;
	}
	~Square()
	{
		cout << "Square::~Square()" << endl;
	}
	virtual Shape* clone() const
	{
		return new Square(*this);
	}
};

class Fred
{
public:
	Fred(Shape* p) : p_(p)
	{
		cout << "Fred::Fred()" << endl;
	}
	~Fred()
	{
		cout << "Fred::~Fred()" << endl;
		delete p_;
	}
	Fred(const Fred& f) : p_(f.p_->clone())
	{
	}
	Fred& operator =(const Fred& f)
	{
		if (this != &f)
		{
			Shape* p2 = f.p_->clone();
			delete p_;
			p_ = p2;
		}
		return *this;
	}

private:
	Shape* p_;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Shape *circle = new Square();
	Fred *fred = new Fred(circle);

	delete fred;
	//delete circle;

	system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值