C++复制构造函数的使用

在C++中对象之间相互复制总是起不到预期的效果,今天呢给大家分享一下区别于浅复制的深复制,可以达到重新开辟内存单元,将被复制的内容完整的拷贝到指定对象的成员变量中去。


深复制的使用背景


1.当类的对象被初始化为同一类的另一对象时
2.当对象被当做一个参数传递给一个函数时
3.当函数返回一个对象时

使用实例
首先其形式同一般构造函数

String(const String &)//复制构造函数声明
/*
*main主函数
*/
#include <iostream>
#include "MyString.h"
#include <string.h>
using namespace std;
void TestStr();
int main()
{
}
void TestStr()
{   String str1("I am LiHua");
    String str2;
    str2 = str1;
    String str3(str1);
    cout << "str1的m_value指针所指向的内容为:" << str1 << endl;
    cout << "str2的m_value指针所指向的内容为:" << str2 << endl;
    cout << "str3的m_value指针所指向的内容为:" << str3 << endl;
}
/*
*MyString头文件
*/
#include <iostream>
#include <string.h>
using namespace std;

class String
{   private:
     int m_length;
     char * m_value;
    public:
      String();
      String(char * str);
      String(const String &);
      ~String();
      friend ostream & operator<<(ostream & ,String &);
      String operator=(const String &);
      
}
/*
*MyString.cpp文件
*/
#include <iostream>
#include "MyString.h"
#include <string.h>
using namespace std;
String::String():m_length(0)
{    this->m_value = new char[m_length + 1];
     this->m_value[0] = '\0';
}
String::String(char * str)
{      this->m_length = strlen(str);
       this->m_value = new char[m_length + 1];
       strcpy(m_value,str);
       cout << *this << endl;
}
ostream & operator<<(ostream & out , String & str)
{   out << str.m_value;
    printf("%p",str.m_value);//打印字符数组指针的地址
    return out;
}
String String::operator=(const String & str)
{   if(this = &str) return *this;
     delete [] m_value;
     m_length = strlen(str.m_value);
     m_value = new char[m_length + 1];
     strcpy(m_value,str.m_value);
     return *this;
}
~String::String()
{ delete [] m_value;  
}

最终可以看到,str1,str2,str3输出结果相同,指针地址不同,即每一个都重新分配了空间,而不是出于同一个指针所指向的空间。达到了复制对象的目的,而不会更改其中一个引起其他对象的更改!

这次内容到这里就结束了,您的三连就是对我最大的支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值