1

我对如何执行 char * 的深拷贝 a 有点困惑。这就是我所拥有的:

Appointment(Appointment& a)
{
  subject = new char;
  *subject = *(a.subject);
}

Appointment(Appointment& b)
{
  location = new char;
  *location = *(b.location);
}

char *subject;
char *location;

我正在尝试执行 char 指针主题和位置的深层副本。这行得通吗?如果没有,有关如何执行此操作的任何建议?

4

4 回答 4

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*是使用 a std::vector<char>,这取决于您想对字符串做什么。

于 2013-05-13T06:17:55.513 回答
2

你可以使用strdup. 因为它在malloc内部使用,所以不要忘记调用free析构函数。

看:

于 2013-05-13T05:59:07.417 回答
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;
};
于 2013-05-13T06:07:06.390 回答
0

不。

您需要分配足够的内存来存储要复制的字符串

subject = new char [strlen(a.subject + 1]; // +1 to allow for null charcter terminating the string.

然后使用strncpy memcpy或复制循环中的所有字符来复制字符串

于 2013-05-13T05:57:30.377 回答