我有一个类:

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/

    10-13 02:15
    查看更多