拷贝

C++类在定义时,系统会提供一个默认的拷贝构造函数,这个函数属于迁拷贝,当使用该类定义对象时赋值,如:类 A = B,就要用到它。一般来说系统提供的默认拷贝函数是不能满足需求的,我们一般要自己编写拷贝构造函数。而拷贝构造函数的定义方法如下:

class 类名

{

    类名(const 类名 &对象名);    // 函数定义

}

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<string.h>
//浅拷贝
class String
{
public:
	String(const char* pStr = "")//构造函数
	{
		if (pStr == NULL)
		{
			_pStr = new char[1];
			*_pStr = '\0';
		}
		_pStr = new char[strlen(pStr) + 1];//strlen不含斜杠0
		strcpy(_pStr, pStr);
	}
	String & operator=(const String &s)
	{
	if (this != &s)
	{
	_pStr = s._pStr;
	}
	return *this;
	}
	~String()
	{
		if (_pStr != NULL)
		{
			delete[] _pStr;
			_pStr = NULL;
		}
	}
private:
	char* _pStr;
};

void FunTest()
{
	String s1;
	String s2("hello");
	String s4(s2);
	String s3;
	s3 = s2;
}
int main()
{
	FunTest();
	system("pause");
	return 0;
}


运行结果:


为什么会出现崩溃呢?


s2、s3和s4中包含的指针指向同一块空间。

浅拷贝】编译器只是直接将指针的值拷贝过来,结果多个对象共用同一块内存,当一个对象将这块内存释放掉之后,另一些对象不知道这块空间已经还给了系统,以为还有效,所以在这段内存进行操作的时候,发生了访问违规。

拷贝】拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。

特点:在拷贝的时候开辟新空间,就不会出现浅拷贝中出现的问题了。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<string.h>
class String
{
public:
		String(const char* pStr = "")//构造函数
		{
			if (pStr == NULL)
			{
				_pStr = new char[1];
				*_pStr = '\0';
			}
			_pStr = new char[strlen(pStr) + 1];//strlen不含斜杠0
			strcpy(_pStr, pStr);
		}
		String(const String &s)//拷贝构造函数
			:_pStr(new char[strlen(s._pStr)+1])
		{
			strcpy(_pStr, s._pStr);
		}
		String & operator=(const String &s)
		{
			if (this != &s)
			{
				String temp(s);
				swap(_pStr, temp._pStr);
			}
			return *this;
		}
		~String()//析构函数
		{
			if (_pStr)
			{
				delete[] _pStr;
				_pStr = NULL;
			}
		}
private:
	char* _pStr;
};
void FunTest()
{
	String s1;
	String s2("hello");
	String s4(s2);
	String s3;
	s3 = s2;
}
int main()
{
	FunTest();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值