如何制作深层照片?

时间:2016-12-28 22:57:13

标签: c++ oop deep-copy

所以基本上我要说我现在有两节课。 1被称为人类,另一个被称为House。

我现在做的是房子制造和摧毁人类,所以基本上在House .h文件中我有

    Human *humanP;

在.cpp文件构造函数中

    humanP = new Human;
    humanP->something(); // lets me access the methods in the Human class

据我所知,这使得一个合成和House创建/破坏了Human对象。但是我需要为我的Human对象添加参数,例如高度和年龄。

主要是我想要像

这样的东西
int age, height;

cout << "Whats your age? << endl;
cin >> age;
cout << "Whats your height? << endl;
cin >> height;

有了这个我想做

Human humanO(age, height);

将使用这些参数创建Human对象。但是我仍然希望将Human对象保存在House类中然后在那里销毁。据我所知,我需要对其进行深层复制,以便我可以在House类中复制humanO,然后删除主文件中的对象。

我一直在寻找示例,但是有很多不同的例子,是否有人可以编写代码看起来像是在main中创建的这个Human对象的深层副本?

编辑:

在这里进行编辑而不是回复导致在此处编写代码更容易。

好的另一个愚蠢的问题。如果我使用简单方法

Human *newPerson = new Human

并做

House house;
house.addHuman(newPerson)

同时使用类方法

addHuman(Human *other)
{
   this->humanP = other;
   cout << humanP->getAge() << endl << endl << endl;
}

它工作正常,给了我年龄。

如果我使用智能指针它不起作用,我应该改变什么?它给了我“无匹配功能”之类的错误。我应该在addHuman()中添加什么参数才能使智能指针变得容易?

1 个答案:

答案 0 :(得分:2)

深度复制仅仅意味着您为第二个副本分配了空间并将原始内容复制到该空间中,而不是浅层副本,这实际上是一个指针&#39;原始对象在原件被销毁后变为无效。

如果您必须拥有多个数据所有者,则只需要一份深层副本。如果您的House对象是拥有数据的,那么创建一个Human' dynamically and then passing it to the House`实例就可以了。

Human *newPerson = new Human(age,height);

house->AddHuman(newPerson);

或者,如果你想利用智能指针:

std::unique_ptr<Person> newPerson = std::make_unique<Person>(age,height);

std::unique_ptr<Person> newPerson(new Person(age,height));

然后

house->AddHuman(std::move(newPerson));

如果您的项目绝对需要执行深层复制,那么您可能不想在本地分配。

house->AddHuman(Person(age,height));

House有一个新方法,AddHuman()看起来像这样:

void House:AddHuman(Person& newHuman);

如果HouseHuman个对象存储在向量中,则可以轻松复制 Human个对象:

m_Humans.PushBack(newHuman);