0

我需要使用复制构造函数对输入对象进行深层复制。我非常卡住...

到目前为止我的代码:

class stringCS   
{   
public:    
     stringCS();
     stringCS(const stringCS &other);

private:
     char *input;
};


stringCS::stringCS(const stringCS &other)
{
}

如何制作深拷贝?我知道我需要使用 for 循环来遍历数组中的所有字符,以将其复制到另一个数组中,最后使用空终止符,但我不了解参数或原始数组的来源。

编辑:

我绝不是在找人给我代码。我正在寻找更多类似于我的问题的伪代码/答案的东西。我不知道如何开始复制,因为我不了解参数。

4

1 回答 1

1

这应该做的工作:

class stringCS   
{
private:
    string input;
public:    
    stringCS(const string& other) : input(other)
    {
    }
};

如果你需要使用 cstrings 这个骨架可能会让你走上正轨

class stringCS   
{
public:    
    stringCS();
    stringCS(const stringCS &other);
    {
        // a) input is a pointer, allocate enough memory
        // you will need to know the size of other (strlen() + 1)
        ...

        // b) copy character by character from `other.input` to `input` in a loop
        // do not forget the final '\0'
        ...
    }
private:
    char *input;
};
于 2013-03-01T19:36:57.047 回答