4.5 运算符重载 赋值运算符 = ;关系运算符== !=,函数调用运算符(),又称仿函数

在这里插入图片描述
在含有堆区数据的对象中,为了避免使用=过程中,出现的重复释放内存的过程中,要将=进行重载,实现深拷贝。

#include<iostream>
using namespace std;

class Person
{
public:
	Person(int age) 
	{
		m_Age = new int(age);
	}
	Person& operator=(const Person &p)//如果在这里,不是返回的自身,程序直接蹦掉,且p2输出乱码。
	//这是因为,返回值时调用拷贝构造函数创建一新的副本,且是简单的值拷贝,即对象中成员m_Age的值是一样的,将p2内存中地址删去,再去操作该地址就是非法操作了。
	//程序崩的原因就是析构函数两次删除同一块内存空间地址
	{
		//应当先判断是否有属性在堆区,如果有先释放干净,然后再深拷贝。
		if (m_Age != NULL){
			delete m_Age;
			m_Age = NULL;
		}
		this->m_Age = new int(*p.m_Age);
		return *this;//返回引用,才是真正的返回自身。为了实现连续=的操作
	}
	~Person()
	{
		if (m_Age != NULL) {
			delete m_Age;
			//m_Age = NULL;
		}
	}
	int* m_Age;
};

void test01()
{
	Person p1(18);
	Person p2(20);
	Person p3(23);
	p3 = p2 = p1;//对象进行赋值操作,此处调用了拷贝构造函数,是浅拷贝
	//浅拷贝造成堆区内存重复释放的问题,因此对=进行重载,实现深拷贝
	cout << "p1的年龄为:" << *p1.m_Age<< endl;
	cout << "p2的年龄为:" << *p2.m_Age << endl;
	cout << "p3的年龄为:" << *p3.m_Age << endl;
	cout << "p1.m_Age的地址为:" << p1.m_Age << endl;
	cout << "p2.m_Age的地址为:" << p2.m_Age << endl;
	cout << "p3.m_Age的地址为:" << p3.m_Age << endl;
}

int main() 
{
	test01();
	system("pause");
	return 0;
}

在这里插入图片描述

#include<iostream>
using namespace std;

class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	//重载 ==
	bool operator == (Person& p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		else { return false; }
	}
	//重载 !=
	bool operator != (Person& p)
	{
		if (this->m_Name != p.m_Name || this->m_Age != p.m_Age)
		{
			return true;
		}
		else { return false; }
	}
	string m_Name;
	int m_Age;
};

void test01()
{
	Person p1("张三", 18);
	Person p2("张三", 18);
	Person p3("李四", 19);
	bool temp = (p1 == p3);
	if (temp) { cout << "此二人相同" << endl; }
	else { cout << "此二人不同" << endl; }

	bool temp1 = (p1 != p3);
	if (temp1) { cout << "此二人不同" << endl; }
	else { cout << "此二人相同" << endl; }
}

int main() {
	test01();
	system("pause");
	return 0;
}

在这里插入图片描述

#include<iostream>
using namespace std;
#include<string>
//仿函数
//打印输出类
class MyPrint
{
public:
	void operator() (string test)
	{
		cout << test << endl;
	}
};
void MyPrint02(string test)
{
	cout << test << endl;;
}
void test01()
{
	MyPrint myPrint;
	myPrint("hello world");//重载了()后,通过对象使用,由于使用起来非常像函数调用,因此称为仿函数
	MyPrint02("hello world");//函数调用
}
//仿函数用起来非常灵活,没有固定的用法
//加法类
class MyAdd
{
public:
	int operator()(int num1,int num2)
	{
		return num1 + num2;
	}
};

void test02()
{
	MyAdd myAdd;
	cout << myAdd(1, 2) << endl;
	//匿名函数对象 不创建对象 通过类名调用仿函数
	//MyAdd()是创建匿名对象,特点:当前行被执行完,立即被释放
	cout << MyAdd()(10, 10) << endl;
}

int main() {
	test02();
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值