C++——运算符重载(下)

4 赋值运算符重载

c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝

如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题

示例:

#include <iostream>
using namespace std;

//赋值运算符重载
//要考虑深浅拷贝的问题

class Person
{
public:
	Person(int num)
	{
		//将数据开辟到堆区
		m_Num = new int(num);
	}

	//对赋值运算符进行重载
	Person & operator=(Person &p)
	{
		if (m_Num != NULL)
		{
			delete m_Num;
			m_Num = NULL;
		}
		//编译器提供的代码是浅拷贝
		//m_Num = p.m_Num;

		//提供深拷贝
		m_Num = new int(*p.m_Num);

		//返回自身
		return *this;
	}

	~Person()
	{
		if (m_Num != NULL)
		{
			delete m_Num;
			m_Num = NULL;
		}
	}
	//数据的指针
	int *m_Num;
};

void test01()
{
	Person p1(10);
	Person p2(20);
	Person p3(30);

	cout << "p1的数据为:" << *p1.m_Num << endl;
	cout << "p2的数据为:" << *p2.m_Num << endl;
	cout << "p3的数据为:" << *p3.m_Num << endl;

	p1 = p2 = p3;

	cout << "p1的数据为:" << *p1.m_Num << endl;
	cout << "p2的数据为:" << *p2.m_Num << endl;
	cout << "p3的数据为:" << *p3.m_Num << endl;
}

int main()
{
	test01();

	system("pause");

	return 0;
}

5 关系运算符重载

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

示例:

#include <iostream>
using namespace std;

class Person
{
public:
	Person(string name, int age)
	{
		this->name = name;
		this->age = age;
	}

	//关系==运算符重载
	bool operator==(Person &p)
	{
		//判断姓名与年龄是否相同
		if (this->name == p.name && this->age == p.age)
		{
			//相同返回true
			return true;
		}
		else
			//不同返回false
			return false;
	}

	//关系!=运算符重载
	bool operator!=(Person &p)
	{
		//判断姓名与年龄是否相同
		if (this->name == p.name && this->age == p.age)
		{
			//相同返回false
			return false;
		}
		else
			//不同返回true
			return true;
	}

	//姓名
	string name;
	//年龄
	int age;
};
//测试案例
void test01()
{
	Person p1("孙大圣", 580);
	Person p2("孙圣", 580);
	//测试==运算符是否重载成功
	if (p1 == p2)
	{
		cout << "True" << endl;
	}
	else
		cout << "False" << endl;

	//测试!=运算符是否重载成功
	if (p1 != p2)
	{
		cout << "True" << endl;
	}
	else
		cout << "False" << endl;
}

int main()
{
	test01();

	system("pause");

	return 0;

}

6 函数调用运算符重载

  • 函数调用运算符 () 也可以重载
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数
  • 仿函数没有固定写法,非常灵活

示例:

class MyPrint
{
public:
	void operator()(string text)
	{
		cout << text << endl;
	}

};
void test01()
{
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");
}


class MyAdd
{
public:
	int operator()(int v1, int v2)
	{
		return v1 + v2;
	}
};

void test02()
{
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名对象调用  
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main() {

	test01();
	test02();

	system("pause");

	return 0;
}
吾生也有涯,而知也无涯
原文地址:https://www.cnblogs.com/daimasanjiaomao/p/13792802.html