赋值运算符重载
系统默认给类提供 赋值运算符写法 是简单值拷贝
导致如果类中有指向堆区的指针,就可能出现深浅拷贝的问题
所以要重载 = 运算符
如果想链式编程 return*this
main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
//一个类默认创建 默认构造、析构、拷贝构造 operator=赋值运算符 进行简单的值传递
class Person
{
public:
Person(int a)
{
this->m_A = a;
}
int m_A;
};
void test01()
{
Person p1(10);
Person p2(0);
p2 = p1; //赋值
cout << "p2 的m_A===" << p2.m_A << endl;//p2 的m_A===10
}
class Person2
{
public:
Person2(char * name)
{
this->pName = new char[strlen(name) + 1];
strcpy(this->pName, name);
}
//重载 = 赋值运算符
Person2& operator= (const Person2 & p)
{
//判断如果原来已经堆区有内容,先释放
if (this->pName != NULL)
{
delete[] this->pName;
this->pName = NULL;
}
//重新开辟新的空间
this->pName = new char[strlen(p.pName) + 1];
strcpy(this->pName, p.pName);
return *this;
}
~Person2()
{
if (this->pName != NULL)
{
delete[] this->pName;
this->pName = NULL;
}
}
char * pName;
};
void test02()
{
Person2 p1("AAAAAAAAA");
Person2 p2("BBBBBBBBB");
Person2 p3("");
p3 = p2 = p1;//会导致重复释放,深拷贝浅拷贝问题,重载“=”解决
cout << "p2.pName=====" << p2.pName << endl;//p2.pName=====AAAAAAAAA
cout << "p3.pName====" << p3.pName << endl;//p3.pName====AAAAAAAAA
//int a = 10;
//int b = 20;
//int c;
//c = a = b; //都是20
//cout << a << " " << b << " " << c << endl;
}
int main(){
//test01();
test02();
system("pause");
return EXIT_SUCCESS;
}