赋值运算符重载

2021-02-22 11:00:19 浏览数 (1)

赋值运算符重载

代码语言:javascript复制
#include<iostream>
using namespace std;
class wood {
public:
	wood(int num) {
		this->num = new int(num);
		cout << "构造函数调用" << endl;
	}
	//赋值运算符重载(赋值拷贝)
	wood& operator=(wood& w1) //w1是要进行拷贝的值
	{
		//浅拷贝
		//num = w.num;
		//深拷贝
		//防止自赋值
		if (this != &w1)
		{
			//如果本身已经在堆区开辟内存,就先释放
			if (num != NULL)
			{
				delete num;
				num = NULL;
			}
			num = new int(*w1.num);
			return *this;
		}
	}
	//析构函数
	~wood() {
		if (num != NULL)
		{
			delete num;
			num = NULL;
		}
		cout << "析构函数调用" << endl;
	}
	int* num;
};
void test()
{
	wood w(10);
	cout << *w.num << endl;
	wood w1(20);
	w1 = w;
	cout << *w1.num << endl;  //在析构函数里面写了delete语句释放内存后,就会造成内存的重复释放,需要进行深拷贝操作
}

int main()
{
	test();
	return 0;
}

注意:

代码语言:javascript复制
#include<iostream>
using namespace std;
class wood {
	friend ostream& operator<<(ostream& cout, wood wood);
public:
	wood(int num) {
		this->num = new int(num);
		cout << "构造函数调用" << endl;
	}
	
	//析构函数
	~wood() {
		if (num != NULL)
		{
			delete num;
			num = NULL;
		}
		cout << "析构函数调用" << endl;
	}
private:
	int* num;
};
ostream& operator<<(ostream& cout, wood wood)
{
	cout << "木头的数量为:" << *wood.num << endl;
	return cout;
}
void test()
{
	wood w(10);
	cout << w << endl;
	
}
int main()
{
	test();
	return 0;
}

当加入了左移重载函数后,在输出cout<<时就已经调用了w的析构函数释放了内存,所以在cout<<w<<endl;会发生错误

0 人点赞