现在的位置: 首页 > 综合 > 正文

拷贝构造与赋值函数

2013年04月06日 ⁄ 综合 ⁄ 共 882字 ⁄ 字号 评论关闭
class CopyTest
{
	int a;
	int b;
	char *pStr;
private:

	//试着把复制成员变量
	void SafeCopyMem(const CopyTest &ct)
	{
		if(this == &ct) //避免同对象复制
			return;

		a=ct.a;
		b=ct.b;
		if(NULL != pStr)
		{
			delete pStr;
			pStr=NULL;
		}

		SafeCopyStr(ct.pStr);

	}

	//安全拷贝字符串
	void SafeCopyStr(const char* str)
	{
		if(str != NULL)
		{
			int len = strlen(str);
			pStr=new char[len+1];
			::memcpy(pStr,str,len); 
			pStr[len] = '\0';
		}
	}

public:

	explicit CopyTest(const char *str, int _a, int _b):pStr(NULL),a(0),b(0)
	{
		SafeCopyStr(str);
		a = _a;
		b = _b;
	}

	CopyTest(const CopyTest &ct):pStr(NULL),a(0),b(0)
	{
		SafeCopyMem(ct);
		//*this=ct;//->不好随着代码复杂的增加,容易人为导致复制构造函数与赋值函数互相调用出现死循环。
	}

	CopyTest& operator=(const CopyTest &ct)
	{
		SafeCopyMem(ct);
		return *this;
	}

	void PrintMem()
	{
		printf("a=%d,b=%d,pStr=%s\n",a,b,(pStr==NULL?"<NULL>":pStr));
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	CopyTest c1("hello",1,2);
	c1.PrintMem();
	CopyTest c2("NULL",4,5);
	c2.PrintMem();

	CopyTest c3(c2);
	c3.PrintMem();

	c1=c3;
	c1.PrintMem();

	c3=c3;
	c3.PrintMem();

	::system("pause");

}

抱歉!评论已关闭.