C ++(逻辑复制构造函数)如何复制对象?

时间:2012-07-19 13:47:51

标签: c++ pointers object copy-constructor

我有一个班级:

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

如何创建复制所有personOne数据的另一个Person对象?年龄指针需要指向一个新的int,所以只要年龄在personOne或personTwo中发生变化,它就不会相互影响。

1 个答案:

答案 0 :(得分:3)

有两个posibilites:

  • 复制构造函数+赋值运算符
  • 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指针吗?
  • 你知道智能指针吗?
  • 你释放了你分配的所有记忆吗?
  • 你是否在构造函数中初始化所有成员?