C/C++教程

C++运算符重载==,<,>,<=,>=

本文主要是介绍C++运算符重载==,<,>,<=,>=,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

,<,<=,>=" href="https://blog.csdn.net/qq_58665528/article/details/122414567" rel="external nofollow" target="_blank">运算符重载==,>,<,<=,>=icon-default.png?t=LBL2https://blog.csdn.net/qq_58665528/article/details/122414567 

以==为例

1. 对于a == b (a.operator==(b)),我们肯定希望b的值不会改,所以要有const修饰,加上希望减少空间开销,提高效率,所以使用引用。所以,参数的类型为const Point&

2. 对于a == b (a.operator==(b)),对于函数的返回值,自然是布尔类型

综上得出bool operator==(const Point& point);

class Point {
private:
	int m_xPosition;
	int m_yPosition;

public:
	Point(int xPosition = 0, int yPosition = 0);		  //构造函数 声明
	bool operator==(const Point& point);				  //重载运算符== 声明
	bool operator<=(const Point& point);				  //重载运算符<= 声明
	bool operator>=(const Point& point);				  //重载运算符>= 声明
	bool operator<(const Point& point);					  //重载运算符<  声明
	bool operator>(const Point& point);					  //重载运算符>  声明

};

//构造函数  定义
Point::Point(int xPosition, int yPosition)
	: m_xPosition(xPosition), m_yPosition(yPosition) {}

//重载运算符== 定义
bool Point::operator==(const Point& point) {
	if (this->m_xPosition == point.m_xPosition && this->m_yPosition == point.m_yPosition)
		return true;
	else
		return false;
}

//重载运算符<= 定义
bool Point::operator<=(const Point& point) {
	if (this->m_xPosition <= point.m_xPosition && this->m_yPosition <= point.m_yPosition)
		return true;
	else
		return false;
}

//重载运算符>= 定义
bool Point::operator>=(const Point& point) {
	if (this->m_xPosition >= point.m_xPosition && this->m_yPosition >= point.m_yPosition)
		return true;
	else
		return false;
}

//重载运算符< 定义
bool Point::operator<(const Point& point) {
	if (this->m_xPosition < point.m_xPosition && this->m_yPosition < point.m_yPosition)
		return true;
	else
		return false;
}

//重载运算符> 定义
bool Point::operator>(const Point& point) {
	if (this->m_xPosition > point.m_xPosition && this->m_yPosition > point.m_yPosition)
		return true;
	else
		return false;
}

这篇关于C++运算符重载==,<,>,<=,>=的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!