关于运算符 前置 ++ 和后置++ (--)

1: 普通函数时

      前置++:参数 是一个非只读的引用类型,返回类型是一个非只读类型的引用。而且必须是先运算后取值

      后置++: 参数是一个非只读的引用类型和一个int型(int型没什么作用,用来区分前置和后置)。返回值是一个普通类 ,先取值后运算(可以用一个无名对象)

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class A{
    int n;
    public:
    A(int n):n(n){}
    int get();
    friend A& operator++(A &a);
    friend A operator++(A &a,int b);
};
A& operator++(A & a)
{
     a.n++;
     return  a;
}
A   operator++(A&a,int b)
{
    return   A(a.n++);
}
int A::get()
{
    return n;
}
int main()
{
     A a=5;
     (++(++a))++;
     cout<<a.get()<<endl;
     A b=a++;
     cout<<b.get()<<" "<<a.get()<<endl;
     system("pause");
     return 0;
}

 2: 函数成员时:

      

     前置++:无参数(有一个隐含的this指针,指向当前对象,)返回类型是一个非只读类型的引用。而且必须是先运算后取值

      后置++: 一个int型(int型没什么作用,用来区分前置和后置)还有一个(隐含的this类型,指向当前对象)。返回值是一个普通类 ,先取值后运算(可以用一个无名对象)

     

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class A{
    int n;
    public:
    A(int n):n(n){}
    int get();
    A& operator++();
    A operator++(int b);
};
A& A::operator++()
{
     n++;
     return  *this;
}
A   A::operator++(int b)
{
    return   A(n++);
}
int A::get()
{
    return n;
}
int main()
{
     A a=5;
     (++(++a))++;
     cout<<a.get()<<endl;
     A b=a++;
     cout<<b.get()<<" "<<a.get()<<endl;
     system("pause");
     return 0;
}

  3:利用友元来写:

   

#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
class A{
    int n;
    public:
    A(int n):n(n){}
    friend int get(A a);
    A& operator++();
    A operator++(int b);
};
A& A::operator++()
{
     n++;
     return  *this;
}
A   A::operator++(int b)
{
    return   A(n++);
}
int get(A a)
{
    return a.n;
}
int main()
{
     A a=5;
     (++(++a))++;
     cout<<get(a)<<endl;
     A b=a++;
     cout<<get(b)<<" "<<get(a)<<endl;
     system("pause");
     return 0;
}

 

转载于:https://www.cnblogs.com/cs1003/archive/2012/12/26/2834213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值