拷贝构造函数
来源:互联网 发布:杨春秋软件俱乐部 编辑:程序博客网 时间:2024/05/19 20:23
拷贝构造函数
拷贝构造函数简单的来说就相当于我们在C语言中的赋值函数
比如:
int n= 1;
Int m=n;
但是在C++中,类相对来说比较复杂,所以一般用拷贝构造函数来实现复制功能。
在拷贝构造函数中,分为两种拷贝,其一是浅拷贝,另外一种是深拷贝。
两者的区别在于:
深拷贝会向堆申请空间,也就是说,构造函数中申请空间,在拷贝函数中也申请空间,这就意味着都有自己的一部分空间。
浅拷贝:在构造函数中申请空间,在拷贝函数中不申请空间,也就是说共用一个空间,进行存储
代码实现:
#include<iostream>
using namespace std;
class String
{
public:
//构造函数初始化
String(const char *Input)
{
if(Input != NULL)
{
Buffer = new char [strlen(Input)+1];
strcpy(Buffer,Input);
}
else
Buffer = NULL;
}
//拷贝函数
String(const String& copy)
{
if(copy.Buffer != NULL)//判断是否为空
{
Buffer = new char [strlen(copy.Buffer)+1];//分配内存
strcpy(Buffer,copy.Buffer);//拷贝复制
}
}
//析构函数
~String()
{
cout << "clear"<<endl;
delete []Buffer;
Buffer = NULL;
}
//字符的长度
int GetLength()
{
return strlen(Buffer);
}
//构造函数
const char *GetString()
{
return Buffer;
}
private:
char *Buffer;
};
int main()
{
String m("hello");
String n=m;//拷贝
cout << m.GetLength()<<endl;
cout << m.GetString() << endl;
cout<<n.GetString()<<endl;
}
- 构造函数、拷贝构造函数
- 拷贝构造函数,构造函数
- 拷贝构造函数--默认拷贝构造函数
- 构造、拷贝构造函数基础
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数(深拷贝,浅拷贝)
- 拷贝构造函数浅拷贝深拷贝
- 拷贝构造函数,浅拷贝,深拷贝
- 拷贝构造函数 深拷贝 浅拷贝
- 拷贝构造函数----深拷贝、浅拷贝
- 拷贝构造函数
- 拷贝构造函数
- 浅析拷贝构造函数
- 拷贝构造函数
- 拷贝构造函数
- C++拷贝构造函数
- C++拷贝构造函数
- 拷贝构造函数
- 视频格式与视频编码压缩标准 之间的关系
- socket编程---fgets和fputs函数使用理解
- XML解析 PULL
- hdoj1084What Is Your Grade?(结构体+sort)
- 运算符.强制类型转换等
- 拷贝构造函数
- mssql中的数据转存到Mysql中
- HDU 5733 tetrahedron (2016 Multi-University Training Contest 1 计算几何)
- mysql的索引
- 类设计原则
- kdtree c++版本
- 杭电5478Can you find it
- mac在安装genymotion下遇到的种种问题
- 关于如何求无向无环图中所有两点之间的长度和