使用复制构造函数进行深度复制

deep copying using copy constructor c++

本文关键字:复制 深度 构造函数      更新时间:2023-10-16

我正在尝试实现我自己的CString类。我在浅拷贝指针时遇到了一些问题。这是类

#include<iostream>
#include<string.h>
using namespace std;
class myCString{
public:
    myCString(){
        m_value = NULL;
    }
    myCString(char* strParam){
        int len = length(strParam);
        m_value = new char[len+1];
        for(int i=0;i<len; i++)
        {
            m_value[i] = strParam[i];
        }
        m_value[len]='';
    }
    myCString(const myCString& obj)
    {
        int len = obj.length();
        m_value = new char[len+1];
        for(int i=0;i<len; i++)
        {
            m_value[i] = obj.m_value[i];
        }
        m_value[len]='';
    }
        myCString(const myCString *obj)
    {
        int len = obj->length();
        m_value = new char[len+1];
        for(int i=0;i<len; i++)
        {
            m_value[i] = obj->m_value[i];
        }
        m_value[len]='';
    }
     const int length() const
    {
        return length(m_value);
    }
    myCString operator=(myCString obj)
    {
        int i=0;
        int length= obj.length();
        m_value = new char[length + 1];
        for(;i<obj.length(); i++)
        {
            m_value[i] = obj.m_value[i];
        }
        m_value[length]='';
        return m_value;
    }
    ~myCString()
    {
        delete []m_value;
        m_value = NULL;
    }
    friend ostream& operator<<(ostream& os, const myCString obj);
private:
    const int length(char* strParam)const
    {
        int i=0;
        while(strParam[i]!=''){
        i++;
        }
        return i;
    }
    char *m_value;
};
ostream& operator<<(ostream& os, myCString obj)
    {
        os<<obj.m_value;
        return os;
    }

,这里是main():

#include"myCString.h"
int main()
{
    myCString *ptr = new myCString("Hi! This is myCStringn");
    cout<<*ptr;
    myCString *ptr2 = ptr;
    delete ptr;
    cout<<*ptr2;
    delete ptr2;
    return 0;
}

问题是当浅拷贝发生时;我知道写

myCString *ptr2 = new myCString(ptr); 

将修复这个问题;但是我想保持main函数的完整性,并在类中做一些改变。有什么办法可以让我做吗?

您的请求是对myCString *ptr2 = ptr行中的对象进行深度复制,但是对象的类编程无法达到这个目的,因为这一行只复制一个指针,不涉及对象的类。如果你想调用复制构造函数,你必须按照你的建议写:myCString *ptr2 = new myCString(ptr);或者你可以这样写:

myCString mystr("Hi! This is myCStringn");
cout<<mystr;
myCString mystr2 =mystr;
cout<<mystr;

另一个问题:调用ostream& operator<<(ostream& os, myCString obj)函数对参数obj调用复制操作符myCString(const myCString& obj)。你应该写

ostream& operator<<(ostream& os, const myCString& obj)
myCString(char* strParam)签名到>

myCString(const char* strParam)