c++重载++和--

转自https://www.cnblogs.com/yangguang-it/p/6486660.html

c++语言并不要求递增和递减运算符必须是类的成员,但是因为它们改变的正好是所操作对象的状态,所以建议将其设定为成员函数。(但下面的代码为了练习,还是分别采用成员函数和全局函数的方式实现)

业余实现代码:

#include<iostream>
using namespace std;
class Test {
    friend Test & operator--(Test &obj);
    friend Test operator--(Test &obj, int);
public:
    Test(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    void display()
    {
        cout << "a:" << a << " b:" << b << endl;
    }
public:
    //前置++
    Test & operator++()
    {
        this->a++;
        this->b++;
        return *this;
    }
    //后置++
    Test operator++(int)
    {
        Test temp = *this;
        this->a++;
        this->b++;
        return temp;
    }
private:
    int a;
    int b;
};
//前置--
Test & operator--(Test &obj)
{
    obj.a--;
    obj.b--;
    return obj;
}

//后置--
Test operator--(Test &obj,int)
{
    Test temp = obj;
    obj.a--;
    obj.b--;
    return temp;
}
int main()
{
    Test t1(1, 2);
    t1.display();
    ++t1;
    t1.display();
    --t1;
    t1.display();
    Test t2(3, 4);
    t2.display();
    t2++;
    t2.display();
    t2--;
    t2.display();
    cout << "hello world!\n";
    return 0;
}

NOTE:

后置版本接受一个额外的参数(不被使用)int类型的参数(必须是int类型的)。当我们使用后置运算符时,编译器为这个形参提供一个值为0的实参。尽管从语法上说后置函数可以使用这个额外的形参,但在实际过程中通常不会这样做。这个形参的唯一作用就是区分前置和后置版本的函数,而不是真的要在实现后置版本是参与运算。因为前置和后置版本的递增或者递减函数原型必须加以一个特殊的区分,c++语言选择增加一个占位参数实现后置版本。

如果我们想要通过函数的方式调用后置版本,则必须为它的整形参数传递一个值。

eg:

a.operator++(0);//调用后置版本,经测试,不用0也行,只要可以转换成int的任意数。

a.operator++();//调用前置版本

专业软件工程师实现方法:

#include<iostream>
using namespace std;
class Test {
    friend Test & operator--(Test &obj);
    friend Test operator--(Test &obj, int);
public:
    Test(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    void display()
    {
        cout << "a:" << a << " b:" << b << endl;
    }
public:
    //前置++
    Test & operator++()
    {
        this->a++;
        this->b++;
        return *this;
    }
    //后置++
    Test operator++(int)
    {
        Test temp = *this;
        ++*this;
        return temp;
    }
private:
    int a;
    int b;
};
//前置--
Test & operator--(Test &obj)
{
    obj.a--;
    obj.b--;
    return obj;
}

//后置--
Test operator--(Test &obj,int)
{
    Test temp = obj;
    --obj;
    return temp;
}
int main()
{
    Test t1(1, 2);
    t1.display();
    ++t1;
    t1.display();
    --t1;
    t1.display();
    Test t2(3, 4);
    t2.display();
    t2++;
    t2.display();
    t2--;
    t2.display();
    cout << "hello world!\n";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/originalcandy/article/details/83509886
今日推荐