复制在C ++中具有自指针的类的构造函数? [英] copy constructor of a class which has self-pointer to itself in C++?

查看:97
本文介绍了复制在C ++中具有自指针的类的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问问我们将如何实现一个以自身指针为其数据成员的类的副本构造函数,我想实现一个深层副本,

I wanted to ask that how will we implement a copy constructor of a class which has self pointer to itself as its data member, i want to implement a deep copy,

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;}


};

我很困惑这行 //如何分配父级
parent = new City(??)
会再次调用构造函数而不是深层复制吗?
问候。

I am confused that this line // how to assign parent parent = new City(??)will call constructor again instead of deep copy? Regards.

推荐答案

怎么样

if (obj.parent != NULL)
    parent = new City(*obj.parent)
else
    parent = NULL;

这应该有效,除非您在父层次结构中有循环。

This should work unless you have cycles in the parent hierarchy.

这篇关于复制在C ++中具有自指针的类的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆