深拷贝&浅拷贝
2016-03-12 18:54
337 查看
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;
}
#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;
}
相关文章推荐
- Python动态类型的学习---引用的理解
- C#中使用DataContractSerializer类实现深拷贝操作示例
- C#中4种深拷贝方法介绍
- 简单谈谈C#中深拷贝、浅拷贝
- 浅拷贝和深拷贝深入理解(shallow copy VS deep copy)
- C#浅拷贝和深拷贝实例解析
- Javascript 浅拷贝、深拷贝的实现代码
- C++拷贝构造函数(深拷贝与浅拷贝)详解
- 浅谈.net平台下深拷贝和浅拷贝
- JavaScript数组深拷贝和浅拷贝的两种方法
- Java中的深拷贝(深复制)和浅拷贝(浅复制)介绍
- Python高级:细说Python浅拷贝和深拷贝
- js的深拷贝,浅拷贝
- PHP浅拷贝、深拷贝简析
- C# 深拷贝
- C# 浅拷贝
- java浅复制和深复制
- oc swift 混编
- 2016郑州大学ACM/ICPC训练赛 Round1
- 单机搭建Android开发环境(一)