0
点赞
收藏
分享

微信扫一扫

C++ 31.类与对象—运算符重载3(关系、函数调用)

彭维盛 2022-03-12 阅读 113

关系运算符重载

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

#include<iostream>
using namespace std;
#include<string>
//重载 关系运算符
class Person
{
public:
	Person(string name, int age)
	{
		m_Name = name;
		m_Age = age;
	}

	//重载  ==  号

	bool operator==(Person &p)//要将返回值的类型改了
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		return false;
	}
	string m_Name;
	int m_Age;

	bool operator!=(Person &p)
	{
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return false;
		}
		return true;
	}
};

void test01()
{
	Person p1("Tom", 18);
	Person p2("Tom", 18);

	if (p1 == p2)	//报错没有匹配的运算符
	{
		cout << "p1和p2是相等的!" << endl;
	}
	else
	{
		cout << "p1和p2是不相等的!" << endl;
	}

	if (p1 != p2)	//报错没有匹配的运算符
	{
		cout << "p1和p2   是   不相等的!" << endl;
	}
	else
	{
		cout << "p1和p2   是   相等的!" << endl;
	}
}
int main()
{
	test01();

	system("pause");
	return 0;
}

函数调用运算符重载

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

#include<iostream>
using namespace std;
#include<string>
//函数调用运算符 重载 
//打印 输出类
class MyPrint
{
public:
	//重载函数调用运算符
	void operator()(string test)  //返回void
	{
		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)    //返回int
	{
		return num1 + num2;
	}
};

void test02()
{
	MyAdd myadd;
	int ret = myadd(100, 100);
	cout << "ret = " << ret << endl;

	//匿名函数对象。 当前函数执行完,立马释放
	cout << MyAdd()(100, 100) << endl;
};
int main()
{
	//test01();
	test02();

	system("pause");
	return 0;
}
举报

相关推荐

0 条评论