C/C++/之运算符重载总结(史上最简单易懂!!!)

所谓重载,就是赋予新的含义。函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。运算符重载(Operator Overloading)也是一个道理,同一个运算符可以有不同的功能。我们以简单的一个点Point类来说明各运算符重载的具体实现,在实际的工作学习中,我们一般根据自己的需求来重写我们自己的运算符重载。

代码如下:

#include 
#include 
#include 

using namespace std;

class Point
{
public:
	 Point():m_x(0),m_y(0){}
	 Point(const int x, const int y)
	 {
		 m_x = x;
		 m_y = y;
	 }
	~Point(){}

	// +运算符重载
	Point operator+ (const Point Lef)
	{
		return Point(this->m_x + Lef.m_x, this->m_y + Lef.m_y);
	}
	//友元 >>重载
	friend istream & operator>>(istream &in, Point &point);
	//友元 <<重载
	friend ostream & operator<<(ostream &out, Point &point);

	//声明为友元函数 全局运算符重载 
	friend Point operator+(const Point &LPoint, const Point &RPoint);
	friend Point operator-(const Point &LPoint, const Point &RPoint);
	friend Point operator*(const Point &LPoint, const Point &RPoint);
	friend Point operator/(const Point &LPoint, const Point &RPoint);

	void display()const
	{
		std::cout << "m_x = " << m_x << "  m_y = " << m_y << std::endl;
	}
private:
	int m_x;
	int m_y;
};

//在全局范围内重载+
Point operator+(const Point &LPoint, const Point &RPoint)
{
	return Point(LPoint.m_x + RPoint.m_x, LPoint.m_y + RPoint.m_y);
}

//在全局范围内重载-
Point operator-(const Point &LPoint, const Point &RPoint)
{
	return Point(LPoint.m_x - RPoint.m_x, LPoint.m_y - RPoint.m_y);
}

//在全局范围内重载*
Point operator*(const Point &LPoint, const Point &RPoint)
{
	return Point(LPoint.m_x * RPoint.m_x, LPoint.m_y * RPoint.m_y);
}

//在全局范围内重载/
Point operator/(const Point &LPoint, const Point &RPoint)
{
	return Point(LPoint.m_x / RPoint.m_x, LPoint.m_y / RPoint.m_y);
}
istream & operator>>(istream &in, Point &point)
{
	in >> point.m_x >> point.m_y;
	return in;
}

ostream & operator<<(ostream &out, Point &point)
{
	out << point.m_x << " + " << point.m_y << " i ";
	return out;
}

int _tmain(int argc, _TCHAR* argv[])
{
	Point pointA(1, 2);
	Point pointB(2, 3);
	std::cout << "PointA's  Values is " << std::endl;
	pointA.display();
	std::cout << "PointB's  Values is " << std::endl;
	pointB.display();

	//调用+ 运算符重载
	Point pointC = pointA + pointB;
	std::cout << "PointC's  + Values is " << std::endl;
	pointC.display();

	//调用- 运算符重载
	Point pointD = pointA - pointB;
	std::cout << "PointD's  -  Values is " << std::endl;
	pointD.display();

	//调用* 运算符重载
	Point pointE = pointA * pointB;
	std::cout << "PointE's  *  Values is " << std::endl;
	pointE.display();

	//调用/ 运算符重载
	Point pointF = pointA / pointB;
	std::cout << "PointF's  +  Values is " << std::endl;
	pointF.display();

	return 0;
}

输出结果如下:

C/C++/之运算符重载总结(史上最简单易懂!!!)_第1张图片

 

你可能感兴趣的:(C++笔记)