运算符重载的主要目的是为了让类对象能像普通数据类型一样能够进行加减乘除,自加自减等操作,非常直观方便。现在来回顾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;
}