C++重载赋值运算符

版权声明: https://blog.csdn.net/qq_40794602/article/details/85229235

C++的类,系统会默认提供,构造函数,拷贝构造函数,析构函数,重载=运算符(浅拷贝),对于含有指针属性的类,如果要用到= 号运算符,我们需要自己进行重载

#include<iostream>
using namespace std;

class Test
{
public:
	Test(const char *t)
	{
		s = new char[strlen(t) + 1];
		strcpy(s, t);
	}
	Test()
	{
		if (s != NULL)
		{
			delete[] s;
		}
	}
	Test& operator=(const Test &item)  //冲澡赋值运算符
	{
		if (s != NULL)
		{
			delete[] s;
			s = NULL;
		}
		s = new char[strlen(item.s) + 1];
		strcpy(s, item.s);

		return *this;  //返回本体,支持链式编程(a = b = c;)
	}
	char *s;
};


int main()
{
	Test t1("我爱罗");
	Test t2("罗爱我");
	Test t3("");
	t3 = t2 = t1;
	cout << "t1:" << t1.s << endl;
	cout << "t2:" << t2.s << endl;
	cout << "t3:" << t3.s << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40794602/article/details/85229235