在C 中具有自我点的类的复制构造函数
copy constructor of a class which has self-pointer to itself in C++?
我想问,我们将如何实现一个具有自我指针自身作为数据成员的类的复制构造函数,我想实现一个深层副本,
class City
{
string name;
City* parent;
public:
City(string nam, double dcov);
City(string nam, double dcov, City* c);
City(const City& obj)
{
this-> name = obj.name;
// how to assign parent
parent = new City(??)
}
~City();
void setName(string name1);
void setDistanceCovered(int dist);
string getName();
double getDistanceCovered();
City* getParent(){return parent;}
};
我感到困惑的是,这条线// how to assign parent
parent = new City(??)
会再次调用构造函数,而不是深副本?问候。
怎么样
if (obj.parent != NULL)
parent = new City(*obj.parent)
else
parent = NULL;
除非您在父层次结构中有周期。
克里斯蒂安的答案非常好。
如果您不用零指针终止链,而是对自我的引用(是您试图用"自我指针自身"来说的?),您可以这样做:
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;}
};
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 复制构造函数、赋值运算符C++
- std::ofstream 作为类成员删除复制构造函数?
- 复制构造函数C++无法正确复制指针
- 关于复制构造函数的一个棘手问题
- 为什么调用复制构造函数而不是移动构造函数?
- 填充上编译器生成的复制构造函数之间的不一致
- C++ 对象指针数组的复制构造函数
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 防止在复制构造函数中隐式调用基构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- 具有已删除移动和复制构造函数的类的就地构造
- 复制构造函数隐式转换问题
- 复制构造函数中的递归调用