重载++,--操作符

运算符重载的主要目的是为了让类对象能像普通数据类型一样能够进行加减乘除,自加自减等操作,非常直观方便。现在来回顾C++的自加减(分前置与后置)以及不等号非运算符,赋值运算符的重载。


class UInt{
public:
	explicit UInt(int i = 0) : m_int(i) { }
	~UInt() { }
	UInt(const UInt &rhs) : m_int(rhs.m_int) { }

public:
	UInt &operator=(const UInt &rhs);

	friend ostream & operator << (std::ostream& os, const UInt& rhs);
	friend UInt operator +(const UInt &lhs, const UInt &rhs);

	//前缀形式返回一个引用,是一个左值
	//后缀形式返回一个const类型,是一个右值,亦即是不能被赋值
	UInt &operator++();
	const UInt operator++(int);
	UInt &operator--();
	const UInt operator--(int);
	UInt& operator+=(int);
private:
	int m_int;
};

ostream & operator << (std::ostream& os, const UInt& rhs)
{
	return os << rhs.m_int;
}

UInt operator +(const UInt &lhs, const UInt &rhs)
{
	UInt result(lhs.m_int + rhs.m_int);
	return result;
}

UInt& UInt::operator =(const UInt &rhs)
{
	m_int = rhs.m_int;
	return *this;
}

//返回一个自身的引用,没有临时对象的代价,性能较高
UInt& UInt::operator ++()
{
	*this += 1;
	return *this;
}

//返回一个临时对象,增加了一个对象构造和析构的代价,性能较低
//由此可见,对于用户自定义类型,应该尽量使用前缀的increment
const UInt UInt::operator ++(int)
{
	UInt oldVal = *this;

	++(*this);

	return oldVal;
}

UInt& UInt::operator --()
{
	*this += (-1);

	return *this;
}

const UInt UInt::operator --(int)
{
	UInt oldVal = *this;

	--(*this);

	return oldVal;
}

UInt& UInt::operator +=(int val)
{
	m_int += val;

	return *this;
}

int main(void)
{
	std::cout << "Hello World!" << std::endl;

	UInt u1(2);
	UInt u2(2);

	//Output 2
	std::cout << "u1++ return " << (u1++) << std::endl;
	//Output 3
	std::cout << "++u2 return " << (++u2) << std::endl;

	//Output 3
	std::cout << u1 << std::endl;
	//Output 3
	std::cout << u2 << std::endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值