如何编写复制构造函数

How to write a copy constructor?

本文关键字:构造函数 复制 何编写      更新时间:2023-10-16

我在弄清楚如何编写我的复制构造函数时遇到了一些麻烦......

这是我的构造函数:

public:
Person(const char * aName, const char * userID, const char * domain, Date aDate) {
//This constructor should create heap objects
    name = new char[strlen(aName) + 1]; 
    strcpy (name, aName);
    emailAddress = new EmailAddress(userID, domain); 
    birthday = new Date(aDate); 
    cout << "nPerson(...) CREATING: ";
    printOn(cout);
}

这就是我试图为我的复制构造函数做的事情:

Person(const Person & p){
    name = new char[strlen(p.name)+1];
    strcpy(name, p.name);
    emailAddress = new EmailAddress(*p.emailAddress);
    birthday = new Date(*p.date);
    cout << "nPerson(const Person &) CREATING: ";
    printOn(cout);
}

我不确定在我的复制构造函数中为我的新日期和新电子邮件地址传递什么,我现在正在做的事情根本不起作用!

这是我的赋值运算符(我不知道在这里再次传递日期和电子邮件地址的内容......

Person & operator=(const Person & p) {
        if(&p != this) {
           delete [] name;
           delete emailAddress;
           delete birthday;
           name = new char[strlen(p.name) + 1];
           strcpy (name, p.name);
               emailAddress = new EmailAddress();
               birthday = new Date();
        }
        return *this;
    }

任何帮助将不胜感激!

编辑:

日期定义

class Date{ //this class is complete
//This class represents a date
public:
      Date(int aDay, int aMonth, int aYear) : day(aDay), month(aMonth), year(aYear) {} 
      Date(const Date & aDate) :  day(aDate.day), month(aDate.month), year(aDate.year)     {};
      void printOn(ostream & out) const {out << day <<"/" << month << "/" << year;}    

我将把JimR的评论分解成一个答案,因为这是一个很好的建议:如果可能的话,使用C++类型,而不是C类型。此外,如果可能,请避免使用指针。

使用C++类型

例如,您的类,尽我们所能,如下所示:

class Person {
    char *name;
    Email *emailAddress;
    Date *birthday;
};

如果DateEmail足够轻量级(它们应该是轻量级),请将它们作为对象本身的值保留;此外,name成为std::string

class Person {
    std::string name;
    Email emailAddress;
    Date birthday;
};

您的构造函数变得非常琐碎:

Person::Person(const std::string &aName, const std::string &userID, const std::string &domain, Date aDate) :
    name(aName),
    emailAddress(userID, domain),
    birthday(aDate)
{ }

更好的是,C++为您制作的默认复制构造函数现在可以正常工作。析构函数赋值运算符也是如此。免费。更好的是,所有这些现在都是异常安全的:如果出于任何原因引发异常,所有内容都将被清理干净。

我让它工作了 - 谢谢大家对我的帮助! 我必须输入*p.emailAddress和*p.birthday

Person(const Person & p){
    name = new char[strlen(p.name)+1];
    strcpy(name, p.name);
    emailAddress = new EmailAddress(*p.emailAddress);
    birthday = new Date(*p.birthday);
    cout << "Person(const & Person)... CREATING: ";
    printOn(cout); 
}
Person & operator=(const Person & p) {
        if(&p != this) {
           delete [] name;
           delete emailAddress;
           delete birthday;
           name = new char[strlen(p.name) + 1];
           strcpy (name, p.name);
           emailAddress = new EmailAddress(*p.emailAddress);
           birthday = new Date(*p.birthday);
        }
        return *this;
    }