克里斯蒂安的回答非常好。
如果您不使用 NULL 指针而是对 self 的引用来终止链(是您试图用“指向自身的自我指针”说的吗?),您可以这样做:
if(obj.parent == NULL)
parent = NULL;
else if(obj.parent==&obj)
parent=this;
else parent = new City(*obj.parent);
如果您有想要避免的循环,则需要使用临时注册映射:
class City
{
string name;
City* parent;
/// The DB to avoid for infinite loops in case of circular references
static
std::map<const City*,City*>& parents_db()
{ static std::map<const City*,City*> ret;
return ret;
}
/// The cloning function that make use of the DB
static
City* clone_parent(const City *_parent)
{ if(_parent)
{ City *& cloned_parent = parents_db()[_parent];
if(!cloned_parent)
cloned_parent = new City(_parent);
return cloned_parent;
}
return NULL;
}
/// The private constructor that make use of the cloning function
City(const City* obj) :
name(obj->name),
parent(clone_parent(obj->parent))
{}
public:
City(string nam, double dcov);
City(string nam, double dcov, City* c);
/// The public constructor that cleans up the DB after cloning the hierarchy
City(const City& obj) :
name(obj.name),
parent(clone_parent(obj.parent))
{ parents_db().clear();
}
~City();
void setName(string name1);
void setDistanceCovered(int dist);
string getName();
double getDistanceCovered();
City* getParent(){return parent;}
};