C++不要求自增或自减一定作为类的成员,但因为这些操作改变操作对象的状态,所以更倾向于将它们作为成员;
为了与内置操作符一致,前缀式操作符应该返回被增量或者减量对象的引用;
后缀形式的自增或自减少操作符接受一个无用的int 形参来与前缀形式区分
为了与内置操作符一致,后缀式操作符应该返回旧值(即尚未自增或者自减的值),并且应该作为值返回,而不是返回引用;
class autoAdd
{
public:
friend std::istream & operator>>(std::istream & , autoAdd &);
friend std::ostream & operator<<(std::ostream &, const autoAdd &);
//default constructor
autoAdd():i(0) { std::cout<<"default constructor of autoAdd is called"<<std::endl;}
//copy control
autoAdd(const autoAdd& m):i(m.i) { std::cout<<"copy constructor of autoAdd is called"<<std::endl;}
autoAdd & operator=(const autoAdd & m) { std::cout<<"operator= of autoAdd is called"<<std::endl; i = m.i; return *this;}
autoAdd& operator++() { std::cout<<"prefix operator++ of autoAdd is called"<<std::endl; ++i; return *this;}
autoAdd operator++(int) { std::cout<<"postfix operator++ of autoAdd is called"<<std::endl; autoAdd ret(*this); i++; return ret;}
autoAdd& operator--() { std::cout<<"prefix operator-- of autoAdd is called"<<std::endl; --i; return *this; }
autoAdd operator--(int) {std::cout<<"postfix operator-- of autoAdd is called"<<std::endl; autoAdd ret(*this); i--; return ret; }
private:
int i;
};
std::istream & operator>>(std::istream & i , autoAdd & a)
{
std::cout<<"operator>> of autoAdd is called"<<std::endl;
i>>a.i;
return i;
}
std::ostream & operator<<(std::ostream & o, const autoAdd & a)
{
std::cout<<"operator<< of autoAdd is called"<<std::endl;
o<<a.i;
return o;
}
// test class autoAdd
autoAdd a1;
std::cout<<a1<<std::endl;
std::cin>>a1;
std::cout<<a1<<std::endl;
++a1;
std::cout<<a1<<std::endl;
a1++;
std::cout<<a1<<std::endl;
std::cout<<a1++<<std::endl;
--a1;
std::cout<<a1<<std::endl;
a1--;
std::cout<<a1<<std::endl;