是否可以在不实现复制构造函数的情况下执行多态深度复制? (其中一个TA表示没有必要实现复制构造函数)

"Suppose you wish to be able to copy an expression object. The problem is that if all you have is an Expression pointer, you don't know what kind of object you actually have, much less what types of objects its fields may be pointing at. Devise a way, given an Expression pointer, to produce an exact (deep) copy of the object it points at."

基类 Expression 没有字段 . 但是其中一个子类包含一个整数字段,另一个子类包含 Expression Pointer 字段 .

我尝试为每个派生对象创建这个虚方法:

virtual ExpressionBinaryOper *clone() const
{return new ExpressionBinaryOper(*this);}

ExpressionBinaryOper类:

class ExpressionBinaryOper : public Expression {
    public:
ExpressionBinaryOper(Expression *left, Expression *right, const string 
    &op);
~ExpressionBinaryOper();
virtual ExpressionBinaryOper *clone() const
  {return new ExpressionBinaryOper(*this);}
void set(string name, int v);
void unset(string name);
string evaluate();
string prettyprint();

private:
    Expression *left;
    Expression *right;
    string oper;
};

并制作克隆:

Expression *theCopy = exp->clone(); //exp is a Expression pointer.

但删除“克隆指针”后,exp也被删除 .