运算符重载(2)

文章详细介绍了如何在C++中重载赋值运算符、关系运算符以及函数调用运算符,涉及内存管理、浅拷贝和深拷贝的概念,通过Person类实例展示了这些操作的应用。
摘要由CSDN通过智能技术生成

1.赋值运算符重载

#include<iostream>
using namespace std;

class Person
{	
	friend void test01();
public:
	Person(int age)
	{
		m_Age = new int(age);
	}


	/*堆区的数据由程序员手动开辟并手动释放*/
	~Person()
	{
		if (m_Age != NULL)
		{
			delete m_Age;
		}
	}

	Person& operator=(Person &p)
	{
		//编译器提供的浅拷贝
		//m_Age = p.m_Age;

		//应该先判断是否有属性在堆区,如果有先释放干净,再深拷贝 p1=p2
		if (m_Age != NULL)
		{
			delete m_Age;
			m_Age = NULL;
		}

		//深拷贝
		 m_Age = new int(*p.m_Age);

		 //返回对象本身
		 return *this;
	}
private:
	int* m_Age;
};

void test01()
{
	Person p1(18);//手动释放后会导致p2对空间的重复释放,违规操作

	Person p2(20);

	Person p3(30);
	//p2=p1返回自身才能使得p3也被赋值
	p3=p2=p1;
	cout << "p1年龄为 " << *p1.m_Age << endl;
	cout << "p2年龄为 " << *p2.m_Age << endl;
	cout << "p3年龄为 " << *p3.m_Age << endl;
}

int main()
{
	test01();
}

2.关系运算符(== !=)的重载

#include<iostream>
using namespace std;
#include<string.h>
#include<stdbool.h>

class Person
{
public:
	Person(string name, int age)
	{
		m_Name = name;
		m_Age = age;
	}

	bool operator==(Person p)
	{	
		if (m_Name == p.m_Name && m_Age == p.m_Age)
		{
			return true;
		}
		else
			return false;

	}

	bool operator!=(Person p)
	{
		if (m_Name == p.m_Name && m_Age == p.m_Age)
		{
			return false;
		}
		else
			return true;
	}
private:
	string m_Name;
	int m_Age;
};


void test01()
{
	Person p1("石暄",38);
	Person p2("石暄", 38);
	//if (p1==p2)
	//{
	//	cout << "两个对象相同" << endl;
	//}
	//else
	//{
	//	cout << "不同" << endl;
	//}
	if (p1 != p2)
	{
		cout << "不等" << endl;
	}
	else
	{
		cout << "相等" << endl;
	}
}

int main()
{
	test01();
}

3.函数调用运算符重载

#include<iostream>
using namespace std;
#include<string.h>

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;
	int ret = myadd(10, 10);
	cout << "ret = " << ret << endl;

	//匿名函数对象MyAdd(特点,当前执行完后立即被释放)
	cout << MyAdd()(100, 100) << endl;
	
}

int main()
{
	/*test01();*/
	test02();
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值