<小甲鱼>C++实例练习27—构造副本构造器

前言:

参考:B站UP主鱼C_小甲鱼<C++快速入门>
代码调试平台:VS2017,调试成功。


问题描述:

问题描述:构造副本构造器


代码实现:

#include <iostream>
#include <string>

using namespace std;

class Myclass
{
public:
	Myclass(int *p);
	Myclass(const Myclass &rhs);
	~Myclass();

	Myclass &operator=(const Myclass &rhs); //对赋值运算符进行重载函数声明
	void print();
private:
	int *ptr;
};
Myclass::Myclass(int *p)
{
	cout << "进入主构造器\n";
	ptr = p;
	cout << "离开主构造器\n";
}
Myclass::Myclass(const Myclass &rhs)
{
	cout << "进入副本构造器\n";
	*this = rhs;
	cout << "离开副本构造器\n";
}
Myclass::~Myclass()
{
	cout << "进入析构器\n";
	delete ptr;
	cout << "离开析构器\n";
}
//a=b
Myclass &Myclass::operator=(const Myclass &rhs)  //对赋值运算符进行重载函数声明
{
	cout << "进入赋值语句重载\n";
	if (this != &rhs)
	{
		delete ptr;

		ptr = new int;
		*ptr = *rhs.ptr;
	}
	else
	{
		cout << "赋值号两边为同个对象,不做处理。";  //a=a情况
	}
	cout << "离开赋值语句重载\n";

	return *this;
}
void Myclass::print()
{
	cout << *ptr << endl;
}

int main()
{
	cout << "----------重载赋值运算符方法----------\n";
	Myclass obj1(new int(1));
	Myclass obj2(new int(2));
	obj2 = obj1;
	obj1.print();
	obj2.print();

	cout << "---------构造副本构造器方法---------\n";

	Myclass obj3(new int(3));
	Myclass obj4 = obj3;
	obj3.print();
	obj4.print();

	cout << "-----------------------------\n";
	Myclass obj5(new int(5));
	obj5 = obj5;
	obj5.print();

	return 0;
}

上一篇:最佳实践扩展Windows窗体DataGridView控件 .net 4.5 附示例代码


下一篇:jQuery加载与选择器