C++重载操作符详解

在C++中有很多的基本运算符,如+,-,*,/,==,>,<等等。这些基本的运算符对于基本的数据类型可以直接拿来使用。那么,涉及到我们自定义的数据类型,比如某些实际开发中的class的时候,如果想要实现这些基本的元素符操作,可能我们需要根据实际情况来进行操作符重载方可进行使用。

一:如下例子
判断连个对象是否相等,比如比较两个人是否同岁。
如下代码:

#include 
using namespace std;

class person
{
public:

	int age;
	bool operator == (const person & ps) const;
	person(int a)
	{
		this->age = a;
	}
};

inline bool person::operator==(const person& ps) const
{
	if (this->age == ps.age)
	{
		return true;
	}
	return false;
}

int main()
{
	person pWWJ(10);
	person pwwj(1);
	if (pWWJ == pwwj)
	{
		cout << "WWJ and wwj is equal" << endl;
	}
	else
	{
		cout << "they are not equal" << endl;
	}

	return 0;
}

上面的例子,我们无法直接比较pwwj和pWWJ这两个对象是否相等,但我们可以做到重载==运算符,然后在实现中比

你可能感兴趣的:(C++,c++)