代码如下:
class base{
base(){}
virtual base* copy()const=0;
virtual ~base(){}
};
class derived:public base{
derived(){}
base* copy()const;
~derived(){}
};
base* derived::copy()const{
return new derived(*this);
}
在函数 copy()
中是否需要使用 new
操作符,还是为什么代码使用了 new
操作符?
我应该像这样直接返回 this
指针吗:
const base* derived::copy()const{
return this;// note: this pointer is const.
}
this
。函数名称暗示它是一个新的对象,与原始对象相同但独立的。 - StoryTeller - Unslander Monicathis
被删除时,可能是一个堆栈对象,这一点是不确定的。 - Joop Eggenclone
而不是copy
。 - galinette