C++ 重载自增和自减操作符

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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值