Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1124374
  • 博文数量: 241
  • 博客积分: 4385
  • 博客等级: 上校
  • 技术积分: 2383
  • 用 户 组: 普通用户
  • 注册时间: 2009-06-07 23:13
文章分类

全部博文(241)

文章存档

2013年(1)

2012年(8)

2011年(62)

2010年(109)

2009年(61)

分类: C/C++

2009-07-27 19:44:17

答案:

在内建数据类型的情况下,效率没有区别;

在自定义数据类型的情况下,++i效率更高!

 

分析:

(自定义数据类型的情况下)

++i返回对象的引用;

i++总是要创建一个临时对象,在退出函数时还要销毁它,而且返回临时对象的值时还会调用其拷贝构造函数。

(重载这两个运算符如下)

class Integer{

public:

    Integer(long data):m_data(data){}

    Integer& operator++(){//前置版本,返回引用

        cout<<” Integer::operator++() called!”<

        m_data++;

        return *this;

    }

    Integer operator++(int){//后置版本,返回对象的值

cout<<” Integer::operator++(int) called!”<

Integer temp = *this;

m_data++;

return temp;//返回this对象的旧值

    }

private:

    long m_data;

};

 

void main(void)

{

    Integer x = 1;//call Integer(long)

    ++x;//call operator++()

    x++;//call operator++(int)

}

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