Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4568506
  • 博文数量: 385
  • 博客积分: 21208
  • 博客等级: 上将
  • 技术积分: 4393
  • 用 户 组: 普通用户
  • 注册时间: 2006-09-30 13:40
文章分类

全部博文(385)

文章存档

2015年(1)

2014年(3)

2012年(16)

2011年(42)

2010年(1)

2009年(2)

2008年(34)

2007年(188)

2006年(110)

分类: C/C++

2006-10-12 15:03:07

c++约定:在增量运算符定义中,放上一个整数形参,就是后增量运算符
 
使用前增量时,对对象(操作数)进行增量修改,然后再返回该对象。   所以前增量运算符操作时,参数与返回的是同一个对象,这与基本数据类型的前增量操作类似,返回的也是左值。
 
使用后增量时,必须在增量之前返回原有的对象值。为此,需要创建一个临时对象,存放原有的对象,以便对操作数(对象)进行增量修改时,保存最初的值。后增量操作返回的是原有对象值,不是原有对象,原有对象已经被增量修改,所以,返回的应该是存放原有对象值的临时对象。
 
当函数返回一个对象时,要创建一个临时对象已存放到返回的对象。
例如:下面的代码中,
Student  fn()
{
 //...
 Student ms("Randy");
 return ms;
}
int main()
{
 Student s;
 s=fn();
 //...
}
一般规定: 创建的临时对象,在整个创建他们的外部表达式范围内有效,否则无效。
也就是说:s=fn(); 这个外部表达式,当fn()返回时产生的临时对象拷贝给s后,临时对象就析构了。
例如:下面的代码中,引用refs不再有效
int main()
{
 Student  &  refs=fn();
}
因为外部表达式"Student &refs=fn();"到分号处结束,以后从fn()返回的临时对象便不再有效,这意味着引用refs
的实体已不存在,所以接下去的任何对refs的引用都是错的。
又例如:下面的代码中,一切临时对象都在一个外部表达式中结束:
Student  fn1();
int  fn2 (Student &);
int main()
{
 int x;
 x=3*fn2(fn1()) +10;
 //...;
}
fn1()返回时,创建临时对象作为fn2()的实参,此时,在fn2()中一直有效 ,当fn2()返回一个int值参与计算表达式时
,那个临时对象仍有效,赋值给x后,则临时对象被析构。
 
 


#include<iostream>
using namespace std;


class Increase
{
    public:
        Increase(int x) :value(x){}
        
        Increase & operator ++();                //前增量

        Increase operator ++(int ); //后增量

        
        void display()
        {
            cout <<"the value is " <<value <<endl;        
        }
        
    private:
        int value;
    

} ;

Increase& Increase::operator ++()
{
    value++;
    
    return *this;
    
}


Increase Increase :: operator ++(int )
{
    Increase temp(*this);
    value++;
    return temp;
}

int main()
{
    Increase n(20);
    
    n.display();
    
    (n++).display();
    
    n.display();
    
    ++n;
    n.display();
    
    ++(++n);
    n.display();
    
    (n++)++;
    n.display();
    
    

}

/*

result is :
the value is 20
the value is 20
the value is 21
the value is 22
the value is 24
the value is 25
*/

阅读(2322) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~