拷贝构造函数

来源:互联网 发布:杨春秋软件俱乐部 编辑:程序博客网 时间: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;

}

0 0
原创粉丝点击