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

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

你可能感兴趣的:(delete,Class,include)