深拷贝&浅拷贝

发布时间:2020-06-23 21:57:29 作者:2013221
来源:网络 阅读:303

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;

}


推荐阅读:
  1. PHP浅拷贝、深拷贝简析
  2. ES6深拷贝与浅拷贝

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

浅拷贝 深拷贝 深拷

上一篇:estore电子商城-知识整合

下一篇:JavaScript编程语言的优势

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》