我对如何执行char *的深层复制感到有些困惑。这就是我所拥有的:
Appointment(Appointment& a)
{
subject = new char;
*subject = *(a.subject);
}
Appointment(Appointment& b)
{
location = new char;
*location = *(b.location);
}
char *subject;
char *location;
我正在尝试执行char指针主题和位置的深层复制。这会有用吗?如果没有,有关如何做到这一点的任何建议吗?
答案 0 :(得分:2)
由于您使用的是C ++,因此您应该使用std::string
来满足您的字符串需求。
您编写的以下代码
Appointment(Appointment& a)
{
subject = new char;
*subject = *(a.subject);
}
不会做您认为会做的事情,在您分配一个字符(new char
)之上,然后将a.subject
的第一个字符分配给它(*subject = *(a.subject)
)
为了复制char*
指向的字符串必须首先确定字符串长度,分配内存以保存字符串然后复制字符。
Appointment(Appointment& a)
{
size_t len = strlen(a.subject)+1;
subject = new char [len]; // allocate for string and ending \0
strcpy_s(subject,len,a.subject);
}
char*
的另一种方法是使用std::vector<char>
,这取决于你想对字符串做什么。
答案 1 :(得分:1)
您可以使用strdup
。由于它在内部使用malloc
,所以不要忘记在析构函数中调用free
。
见:
答案 2 :(得分:1)
您必须跟踪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;
};
答案 3 :(得分:0)
没有
您需要分配足够的内存来存储要复制的字符串
subject = new char [strlen(a.subject + 1]; // +1 to allow for null charcter terminating the string.
然后使用strncpy
memcpy
或复制循环中的所有字符以复制字符串