我有一个类:
class Person{
public:
Person();
~Person();
string name;
int* age;
};
int main()
{
Person* personOne = new Person;
personOne->name = "Foo";
personOne->age = new int(10);
return 0;
}
如何创建另一个Person对象复制所有personOne数据?年龄指针需要指向一个新的int值,因此,只要personOne或personTwo中的年龄发生变化,它就不会相互影响。
最佳答案
有两种可能性:
clone
方法码:
class Person{
public:
Person();
~Person();
Person (const Person& other) : name(other.name), age(new int(*(other.age)))
{
}
Person& operator = (const Person& other)
{
name = other.name;
delete age; //in case it was already allocated
age = new int(*(other.age))
return *this;
}
//alternatively
Person clone()
{
Person p;
p.name = name;
p.age = new int(age);
return p;
}
string name;
int* age;
};
在继续操作之前,请回答以下问题:
int
指针吗? 关于c++ - C++(逻辑复制构造函数)如何复制对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11562282/