我正在检查c ++中的工厂设计模式。我了解了为什么要使用克隆方法:
尽管基因工厂生产了通用士兵的克隆 前景非常可怕,克隆C对象是无害且有用的 大部分时间都是活动。这里的目标与 到目前为止,我们所处理的是:我们不必从 从头开始。我们有一个指向多态对象的指针, 喜欢创建它的精确副本。因为我们不完全了解 类型的多态对象,我们不完全知道是什么新对象 创建,这是实际的问题。 Quote
我不了解的部分是函数return new Line(*this);
中的virtual Line* Clone() const
。你能告诉我我的解释是否正确吗?
Shape* Create(const std::string& key) const
中,我们称为tmp=((*it).second)->Clone();
Line(const Line &)
并将其作为参数传递。但是由于this
一个指针,我们必须取消引用它,因为我们通过引用将其传递给副本构造函数。return new Line()
而不是return new Line(*this)
会发生什么?我们不会返回对象的副本而是一个新对象?这是一种愚蠢和错误。为什么要创建新对象,因为它已经存在public:
virtual Shape* Clone() const = 0;
...
};
class Line : public Shape
{
public:
virtual Line* Clone() const
{
return new Line(*this);
}
...
};
//The create function is from the Factory
Shape* Create(const std::string& key) const
{
Figure* tmp=0;
std::map<string, Figure*>::const_iterator it=m_map.find(key);
if(it!=m_map.end())
{
tmp=((*it).second)->Clone();
}
return tmp;
}
答案 0 :(得分:1)
表达式new Line(*this)
创建一个新的Line
对象,并使用Line
copy-constructor 构造新对象。
那应该准确复制*this
,即克隆*this
。
当然,要使其全部正常工作,请考虑使用the rules of three, five and zero。
答案 1 :(得分:0)
假设我们使用return new Line()而不是return new Line(* this)会发生什么?
Ans:它将创建使用默认构造函数创建的Line的新对象,该默认构造函数可能与您用来调用clone方法的对象不同。因此,如果要将对象克隆到调用对象,则需要使用复制构造函数(即,使用代码new Line(*this)