operator=返回对象和引用的区别

class CTest
{
public:
	CTest()
	{
		printf("Constructor function is executed now!\n");
	}

	CTest(int nID)
	{ 
		printf("Constructor function with parameter is executed now!\n");
		m_nID = nID;
	}

	~CTest()
	{
		printf("Destructor function is executed now!\n");
	}

	CTest(const CTest& test)
	{
		printf("Copy constructor function is executed now!\n");
		m_nID = test.m_nID;
	}

	/// <summary>
	/// 	1,如果是返回对象,则先调用operator=,然后调用拷贝构造函数;
	///		2,如果返回引用,则只是调用operator=,效率更高
	/// </summary>
	CTest& operator=(const CTest& test)
	{
		printf("Assignment constructor function is executed now!\n");
		m_nID = test.m_nID;
		return *this;
	}

	void printID()
	{
		printf("m_ID = %d\n", m_nID);
	}

private:
	int m_nID;
};

int _tmain(int argc, _TCHAR* argv[])
{
	//case1
	//{
	//	CTest test1(1);
	//	CTest test2, test3;
	//	test3 = test2 = test1;
	//}

	//case2
	{
		CTest test1(2);
		CTest *pTest2 = new CTest(test1);	//只调用拷贝构造函数
		delete pTest2;
	}

	getchar();
	return 0;
}


对于case1,执行结果如下:


对于case2,执行结果如下:



阅读更多
个人分类: C++
上一篇用SAXXMLReader将XML文件保存为缩进格式,方便阅读
下一篇Dll分配的内存块,应用释放的问题
想对作者说点什么? 我来说一句

父类引用指向子类对象

2015年06月25日 32KB 下载

没有更多推荐了,返回首页

关闭
关闭