[英]Deep copy dynamically allocated object in C++
大家好,我找不到为动态分配的对象构建适当的副本构造函数的方法。 它大喊: error: no matching function for call to 'Person::(Person*&')
我的测试代码是这样的:
#include <iostream>
#include <cstring>
class Person
{
private:
int* age;
std::string name;
public:
Person(std::string name_in, int age_in);
Person(const Person& other);
~Person();
void printAge();
void printName();
};
Person::Person(std::string name_in, int age_in)
{
std::cout << "Creating person named " << name_in << std::endl;
name = name_in;
age = new int;
*age = age_in;
}
Person::Person(const Person& other)
{
std::cout << "Copying person." << std::endl;
age = new int;
*age = *other.age;
name = other.name;
}
Person::~Person()
{
std::cout << "Freeing memory!" << std::endl;
delete age;
}
void Person::printAge()
{
std::cout << "The age is " << *age << std::endl;
}
void Person::printName()
{
std::cout << "The name is " << name << std::endl;
}
int main()
{
Person* person1 = new Person("Ramon", 19);
person1->printAge();
person1->printName();
Person* person2 = new Person(person1);
person2->printAge();
person2->printName();
delete person1;
delete person2;
return 0;
}
似乎在创建person2对象时,它只是指向person1的指针,但不是! 我说这是一个新的动态分配的对象: Person* person1 = new Person("Ramon", 19);
。 知道这可能是什么原因吗?
谢谢。
复制构造函数通过引用而不是指针接受输入参数。
更改此:
Person* person2 = new Person(person1);
对此:
Person* person2 = new Person(*person1);
确保确保也编写自己的赋值运算符。 它与复制构造函数相似,但是除了内容的深层复制外,它还返回对调用对象的引用。
已定义的副本构造函数为
人(const Person&other)
该方法签名接受对人员对象的引用,因此您需要发送一个引用。
在代码中,您要发送person1 ,它是新操作员分配的指针。
如果要从另一个对象的指针复制一个对象,则应该制作这样的方法。
Person::Person(const Person *other)
{
std::cout << "Copying person." << std::endl;
age = new int;
*age = *other->age;
name = other->name;
}
但这不是复制构造函数通常具有的方法签名,并且在诸如以下情况下不会复制
人p2 =人1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.