您必须跟踪char*
长度才能制作它们的副本,例如:
class Appointment
{
public:
char *subject;
int subject_len;
char *location;
int location_len;
Appointment() :
subject(NULL), subject_len(0),
location(NULL), location_len(0)
{
}
~Appointment()
{
delete[] subject;
delete[] location;
}
Appointment(const Appointment& src) :
subject(new char[src.subject_len]), subject_len(src.subject_len),
location(new char[src.location_len]), location_len(src.location_len)
{
std::copy(src.subject, src.subject + src.subject_len, subject);
std::copy(src.location, src.location + src.location_len, location);
}
Appointment& operator=(const Appointment& lhs)
{
delete[] subject;
subject = NULL;
delete[] location;
location = NULL;
subject = new char[lhs.subject_len];
subject_len = lhs.subject_len;
std::copy(lhs.subject, lhs.subject + lhs.subject_len, subject);
location = new char[lhs.location_len];
location_len = lhs.location_len;
std::copy(lhs.location, lhs.location + lhs.location_len, location);
}
};
在这种情况下,您最好std::string
改用:
class Appointment
{
public:
std::string subject;
std::string location;
Appointment()
{
}
Appointment(const Appointment& src) :
subject(src.subject), location(src.location)
{
}
Appointment& operator=(const Appointment& lhs)
{
subject = lhs.subject;
location = lhs.location;
}
};
这可以进一步简化,因为编译器生成的默认构造函数和赋值运算符足以自动为您深度复制值:
class Appointment
{
public:
std::string subject;
std::string location;
};