C++ 的 +,加号重载示例

#include <iostream>

// overloading "operator + "
// 要考虑加法的形式
// a+1
// a+a
// 1+a

//////////////////////////////////////////////////////////

class Rectangle
{
public:
	Rectangle(const int w, const int h) 
		: width(w), height(h)
	{};

	~Rectangle() {};
	Rectangle operator+ (const int& i) const;			// a+1,这里不能返回引用
	Rectangle operator+ (const Rectangle& i) const;		// a+a
														// 1+a,定义在class之外

public:
	int width;
	int height;
};


//////////////////////////////////////////////////////////

Rectangle
Rectangle::operator+(const int& i) const				// a+1
{
	Rectangle r(*this);
	r.width += i;
	r.height += i;

	return r;
}

Rectangle
Rectangle::operator+(const Rectangle& rec) const		// a+a
{
	Rectangle r(*this);
	r.width += rec.width;
	r.height += rec.height;

	return r;
}


//////////////////////////////////////////////////////////

std::ostream&
operator<< (std::ostream& os, const Rectangle& rec)
{
	os << rec.width << ", " << rec.height;
	return  os;

}


Rectangle
operator+(const int i, const Rectangle& rec)			// 1+a
{
	Rectangle r(rec);
	r.width += i;
	r.height += i;

	return r;
}


//////////////////////////////////////////////////////////

int main()
{
	Rectangle a(40, 10);
	
	std::cout << "a+1 = " << a + 1 << std::endl;
	std::cout << "a+a = " << a + a << std::endl;
	std::cout << "1+a = " << 1 + a << std::endl;


	// 这种形式,先计算1+a,然后a+a,最后a+1。
	std::cout
		<< "a+1 = " << a + 1 << std::endl		
		<< "a+a = " << a + a << std::endl		
		<< "1+a = " << 1 + a << std::endl		
		;
	

	return 0;
}

  

原文地址:https://www.cnblogs.com/alexYuin/p/11965972.html