C++ class 外的 ++ 重载,左++,右++,重载示例。

#include <iostream>

// overloading "operator ++ " outside class
// ++ 是一元操作符

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

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

	~Rectangle() {};

public:
	int width;
	int height;
};


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



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

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

}


Rectangle &
operator++ (Rectangle& ths)
{
	ths.height++;
	ths.width++;
	return  ths;
}

Rectangle
operator++ (Rectangle& ths, int)
{
	Rectangle b(ths);
	++(ths);
	return  b;
}

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

int main()
{
	Rectangle a(40, 10);
	Rectangle b = (a++);
	std::cout
		<< "a = " << a << std::endl		// 输出 41, 11
		<< "b = " << b << std::endl		// 输出 40, 10
		;
	Rectangle c = (++a);

	std::cout
		<< "a = " << a << std::endl		// 输出 42, 12
		<< "b = " << b << std::endl		// 输出 40, 10
		<< "c = " << c << std::endl		// 输出 42, 12
		;

	std::cout
		<< "a = " << a << std::endl		// 输出 43, 13
		<< "a = " << ++a << std::endl	// 输出 43, 13
		;

	std::cout
		<< "a = " << (a++) << std::endl	// 输出 43, 13
		;

	// C++ 自带的 ++ 作用结果

	{
		int vint = 0;
		std::cout
			<< "v = " << vint << std::endl;		// 输出 0
		std::cout
			<< "v = " << vint << std::endl		// 输出 1
			<< "v = " << vint++ << std::endl;	// 输出 1
	}

	{
		int vint = 0;
		std::cout
			<< "v = " << vint << std::endl;		// 输出 0
		std::cout
			<< "v = " << vint << std::endl		// 输出 1
			<< "v = " << ++vint << std::endl;	// 输出 1
	}

	return 0;
}

  

++i,应该是先自加一,返回自身(已经加1之后的自身);

i++,应该是先拷贝自身,再自加一,返回自身的拷贝(自己已经加1,但是拷贝没有)。

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