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

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. 运行结果: 

【C++】重载前置++和后置++_第1张图片

5. 源代码 

#define _CRT_SECURE_NO_WARNINGS
#include 
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;
}         

你可能感兴趣的:(c++,蓝桥杯,开发语言)