i++与++i哪个效率更高?

来源:互联网 发布:单片机流水灯 编辑:程序博客网 时间:2024/05/01 03:16

答案:

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

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

分析:

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

++i返回对象的引用;

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

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

class Integer{

public:

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

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

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

        m_data++;

        return *this;

    }

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

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

        Integer temp = *this;

        m_data++;

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

    }

private:

    long m_data;//long的封装

};

void main(void)

{

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

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

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

}

原创粉丝点击