深拷贝&浅拷贝

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深拷贝&浅拷贝相关的知识,希望对你有一定的参考价值。

STRING.h文件


#pragma once

#include<string.h>

class String

{

public:

String(char* str="")      //深拷贝

:_str(new char[strlen(str)+1])

{

strcpy(_str, str);

cout << "构造函数 " << endl;

}

~String()

if (_str!=NULL)

{

delete[]_str;

}

cout << "析构函数" << endl;

}

String(const String& s)      //深拷贝

:_str(new char[strlen(s._str) + 1])

{

strcpy(_str, s._str);

cout << "拷贝构造函数" << endl;

}


/*String(const String& s)

:_str(NULL)

{

String tmp(s._str);

swap(_str, tmp._str);

}*/


String &operator=(const String& s)

{

if (this != &s)       //传统写法,有弊端

{

/*delete[]_str;

_str = new char[(strlen(s.str) + 1)];//----如果没有空间怎么办

strcpy(_str, s._str);*/



char *tmp = new char[strlen(s._str) + 1];//现代写法

strcpy(tmp, s._str);

delete[] _str;

_str = tmp;


cout << "赋值运算符重载" << endl;

return *this;

}

private:

char* _str;

};



test.cpp文件


#include<iostream>

using namespace std;

#include"STRING.h"



int main()

{

String s1;

String s2("abcd");

s1 = s2;

String s3 = s2;

int i = 0;

system("pause");

return 0;

}


本文出自 “学习记录” 博客,请务必保留此出处http://10794428.blog.51cto.com/10784428/1750310

以上是关于深拷贝&浅拷贝的主要内容,如果未能解决你的问题,请参考以下文章

IOS 深拷贝和浅拷贝

VUE开发 - 深拷贝与浅拷贝探讨

什么是深拷贝和浅拷贝以及如何实现深拷贝

深拷贝和浅拷贝的区别?

Python3 & 浅拷贝与深拷贝

C#的浅拷贝和深拷贝