【C++】重载前置++和后置++

本文详细讲解了如何在Point类中实现++运算符的前后置重载,并通过示例展示了在main函数中使用这些重载操作符后的输出结果。

1. Point类:

class Point
{
public:
    Point(float xx, float yy) :x(xx), y(yy) {}
    void Show() //显示输出函数
    {
        cout << "[" << x << "," << y << "]";
    }
private:
    float x, y;
};
int main()
{
    //创建两个Point对象
    Point a(1 , 2);
    Point b(2, 3);
}

2. 我们要实现: 

b = a++;  //先将a赋给b,a自身再加1  b:[1, 2]  a:[2, 3]

b = ++a;  //先将a自身加1,再将a赋给b  b:[2, 3]  a:[2, 3]

测试的main函数: 

int main()
{
    //创建两个Point对象
    Point a(1 , 2);
    Point b(2, 3);

    //测试++的重载
    b = a++;
    cout << "后置++后b为:";
    b.Show();
    cout << endl;
    cout << "后置++后a为:";
    a.Show();

    cout << endl;
    cout << "---------------------";
    cout << endl;

    b = ++a;
    cout << "前置++后b为:";
    b.Show();
    cout << endl;
    cout << "前置++后a为:";
    a.Show();
    cout << endl;
}

 3. 将++运算符重载为成员函数:

//后置++
Point operator++(int)
    {
        Point c = *this;  //将加之前的对象保存在临时变量里
        x = x + 1;
        y = y + 1;
        return c; //返回加之前的对象
    }

//前置++
Point operator++()
    {
        (*this)++;  //前面后置++已经写好,所以这里调用的是重载的后置++
        return *this;  //返回当前对象
    }

4. 运行结果: 

5. 源代码 

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;

class Point
{
public:
    Point(float xx, float yy) :x(xx), y(yy) {}
    Point operator++(int)
    {
        Point c = *this;  //将加之前的对象保存在临时变量里
        x = x + 1;
        y = y + 1;
        return c; //返回加之前的对象
    }
    Point operator++()
    {
        (*this)++;  //前面后置++已经写好,所以这里调用的是重载的后置++
        return *this;  //返回当前对象
    }
    void Show()
    {
        cout << "[" << x << "," << y << "]";
    }
private:
    float x, y;
};

int main()
{   
    Point a(1, 2);
    Point b(3, 4);
    

    b = a++;
    cout << "后置++后b为:";
    b.Show();
    cout << endl;
    cout << "后置++后a为:";
    a.Show();

    cout << endl;
    cout << "---------------------";
    cout << endl;

    b = ++a;
    cout << "前置++后b为:";
    b.Show();
    cout << endl;
    cout << "前置++后a为:";
    a.Show();
    cout << endl;
    return 0;
}         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值