zoukankan      html  css  js  c++  java
  • ++i和i++的效率孰优孰劣

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

    在自定义数据类型的情况下,++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)

    }

  • 相关阅读:
    2020暑假牛客多校9 B
    2020暑假牛客多校10 C -Decrement on the Tree (边权转点权处理)
    HDU 5876 补图的最短路
    CSP初赛复习
    遗传算法
    排列组合
    和式 sigma的使用
    多项式的各种操作
    三分
    NOIP2018普及游记
  • 原文地址:https://www.cnblogs.com/xiemingjun/p/9633647.html
Copyright © 2011-2022 走看看