(c++常问问题二)赋值构造函数(重载赋值操作符)

*什么是赋值构造函数(重载赋值操作符)

下面的代码演示了什么是赋值构造函数,如果不人为定义赋值构造函数,系统将默认给你分配一个浅拷贝的赋值构造函数(下面例子为深拷贝的赋值操作)

 

class cat
{
public:
	//构造函数
	cat():m_pMyName(NULL),m_unAge(0)
	{
		cout<<"cat defult ctor"<<endl;
	}

	//子类赋值构造函数(重载赋值操作符)
	cat& operator=(cat& other)
	{
		this->m_unAge = other.m_unAge;

		//把自己的空间释放先
		if (0 != this->m_pMyName)
		{
			delete this->m_pMyName;
			this->m_pMyName = NULL;
		}

		//如果目标有名字
		if (other.m_pMyName)
		{
			//动态分配一个名字长度+1的堆..此处为深拷贝
			int len = strlen(other.m_pMyName);
			m_pMyName = new char[len + 1];
			memset(m_pMyName , 0 , len+1);
			memcpy(m_pMyName , other.m_pMyName , len+1);
		}

		/*
		//如果目标有名字
		if (other.m_pMyName)
		{
			//动态分配一个名字长度+1的堆..此处为浅拷贝..只复制了指针,没复制指针指向的对象
			m_pMyName = other.m_pMyName;
		}
		*/
		return *this;
	}

	unsigned int m_unAge;
	char* m_pMyName;
};

//实战演练
void main()
{
    cat A;
    cat B = A; //复制拷贝函数
    cat C(A);//复制拷贝函数
    cat D;
    D = A;//赋值构造
}

 

结论:通常定义了拷贝构造函数,赋值操作符也要同时重载...而当需要手动写这两个函数时,析构函数大部分情况下也是必要的

posted @ 2016-01-28 23:47  Jensen抹茶喵  阅读(341)  评论(0编辑  收藏  举报