如何编写复制构造函数
How to write a copy constructor?
我在弄清楚如何编写我的复制构造函数时遇到了一些麻烦......
这是我的构造函数:
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;
};
如果Date
和Email
足够轻量级(它们应该是轻量级),请将它们作为对象本身的值保留;此外,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;
}
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类