自增运算符重载

//前置++是把对象加1后再给你用。

//后置++是把对象的值借你用,再把对象本身加1。


1.作为成员函数:

前缀自增运算符

    test operator++() //前置运算符
    {
        this->value++;
        return *this;
    }

后缀自增运算符

    test operator++(int) //后置运算符
    {
        test temp(*this);  //将对象的值赋给临时建立的对象
        this->value++;
        return temp;       //返回临时建立的对象,
    }



2.作为友元函数:

先要在类内声明友元函数

    friend test operator++(test& a);
    friend test operator++(test& a,int);
然后再类外定义

test operator++(test& a) //前置运算符
{
    a.value++;
    return a;
}

test operator++(test& a,int) //后置运算符
{
    test temp(a);
    a.value++;
    return temp;
}





代码:


#include <iostream>
#include <string>

using namespace std;

//前置++是把对象加1后再给你用
//后置++是把对象的值借你,再把对象本身加1


class test
{
    int value;
public:
    test():value(0){}      //无参构造函数
    test(int n):value(n){} //有参...
    friend ostream& operator<<(ostream& output,test a); //重载插入运算符
    friend istream& operator>>(istream& input,test& a); //重载提取运算符

    test operator++() //前置运算符
    {
        this->value++;
        return *this;
    }

    test operator++(int) //后置运算符
    {
        test temp(*this);
        this->value++;
        return temp;
    }

};

ostream& operator<<(ostream& output,test a)
{
    output<<a.value;
    return output;
}

istream& operator>>(istream& input,test& a)
{
    cout<<"请输入对象的值value: ";
    input>>a.value;
    return input;
}

int main ()
{
    test a;
    cin>>a;
    cout<<"++a "<<++a<<endl;
    cout<<"a++ "<<a++<<endl;
    cout<<"a   "<<a<<endl;

    return 0;
}




posted @ 2017-12-11 19:17  詹晔晔(๑>؂<๑)  阅读(187)  评论(0编辑  收藏  举报