2013-03-01 79 views
0

我需要使用复制构造函数对输入对象进行深层复制。我非常卡住......制作复制构造函数,使输入对象的深层副本(使用数组)

到目前为止我的代码:

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

private: 
    char *input; 
}; 


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

我如何去制作深层副本?我知道我需要使用for循环遍历数组中的所有字符,并将其复制到另一个数组中,并在末尾使用空终止符,但我不明白参数或原始数组的来源。

编辑:

我不是在寻找某人给我的代码。我正在寻找更多符合我的问题的伪代码/答案。我不知道如何开始复制,因为我不明白这个参数。

回答

1

这应该做的工作:如果您需要使用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; 
}; 
+0

我相信会的工作,但我真正需要使用

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

一个for循环将数据复制到一个数组中... – Rachel 2013-03-01 20:05:07

+0

我不确定给你的解决方案是一件好事,所以我会提供一些提示:a)你需要分配足够的内存来存储字符字符串(包括最终'\ 0')b)可以将字符从字符串复制到ch ar *(并添加最后的'\ 0',因为该字符串不包含一个)。我希望有所帮助。 – 2013-03-01 20:55:13

+0

好的。我有这样的代码,但我只是不想放弃它...有没有办法我可以私下发送给你?我得到一个错误,说'没有操作符'[]'匹配这些操作数'我可以不使用其他[索引]?它不是一个数组? – Rachel 2013-03-02 00:25:15