重载operator++

参考:www.cnblogs.com/ggggg63/p/6693008.html

(作为成员函数的)前置“++”不接受任何参数,而后置“++”接受一个int类型的参数,尽管没什么实际用途,但是却为编译器确定重载对象提供了帮助。

还有一点,则是需要特殊小心地处理返回值问题。前置++通常情况应该返回对象的引用,而后置式的++应该返回一个const修饰的对象实体。

1. 一般重载为成员函数
//prefix ++ : increment and fetch
myclass & myclass::operator++()
{
    *this += 1;
    return *this;
}
//postfix ++ : fetch and increment
const myclass myclass::operator++(int)
{
    myclass tmp = *this;
    ++(*this);
    return tmp;
}

2. 也可重载为非成员函数(很少这么做)
friend myclass& operator(myclass& a); // 前++
friend myclass  operator(myclass& a, int); //后++

  

  例子:

class point
{
public:
    point(int val)
    {
        x=val;
    }
    //(作为成员函数的)前置“++”不接受任何参数,而后置“++”接受一个int类型的参数,
    //尽管没什么实际用途,但是却为编译器确定重载对象提供了帮助。
    point& operator++() //前++
    {
        x++;// this->x += 1;
        return *this;
    }
    const point operator++(int) //后++
    {
        point old=*this;
        ++(*this);
        return old;
    }
    int GetX() const
    {
        return x;
    }
private:
    int x;
};
int main()
{
    point a(10);
    cout<<(++a).GetX();
    cout<<a++.GetX();
    return(0);
}
// 结果: 1111

  

转载于:https://www.cnblogs.com/htj10/p/10186047.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值