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

#include <iostream>

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

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

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

	~Rectangle() {};


	Rectangle& operator++ ();	// ++i
	Rectangle operator++ (int); // i++

public:
	int width;
	int height;
};


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


Rectangle &
Rectangle::operator++ ()
{
	this->height++;
	this->width++;
	return  *this;
}

// 返回类型不能是引用。为了使 i++ 的效果和默认类型一致
Rectangle
Rectangle::operator++ (int)
{
	Rectangle b(*this);
	++(*this);
	return  b;
}


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

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

}


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

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,但是拷贝没有)。

 

posted @ 2019-12-01 11:32  路边的十元钱硬币  阅读(653)  评论(0编辑  收藏  举报