zoukankan      html  css  js  c++  java
  • C++中自定义类2种自增运算的代码实现和区别

    本文首发于个人博客https://kezunlin.me/post/caef83a3/,欢迎阅读最新内容!

    cpp i++ vs ++i for user defined class

    Guide

    code

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <vector>
    #include <iostream>
    using namespace std;
    
    class Integer
    {
    public:
        Integer(int value): v(value)
        {
            cout << "default constructor" << endl;
        }
        Integer(const Integer &other)
        {
            cout << "copy constructor" << endl;
            v = other.v;
        }
        Integer &operator=(const Integer &other)
        {
            cout << "copy assignment" << endl;
            v = other.v;
            return *this;
        }
    
        // ++i  first +1,then return new value
        Integer &operator++()
        {
            cout << "Integer::operator++()" << endl;
            v++;
            return *this;
        }
    
        // i++  first save old value,then +1,last return old value
        Integer operator++(int)
        {
            cout << "Integer::operator++(int)" << endl;
            Integer old = *this;
            v++;
            return old;
        }
    
        void output()
        {
            cout << "value " << v << endl;
        }
    private:
        int v;
    };
    
    void test_case()
    {
        Integer obj(10);
        Integer obj2 = obj;
        Integer obj3(0);
        obj3 = obj;
        cout << "--------------" << endl;
        cout << "++i" << endl;
        ++obj;
        obj.output();
        cout << "i++" << endl;
        obj++;
        obj.output();
    }
    
    int main()
    {
        test_case();
        return 0;
    }
    

    output

    default constructor
    copy constructor
    default constructor
    copy assignment
    --------------
    ++i
    Integer::operator++()
    value 11
    i++
    Integer::operator++(int)
    copy constructor
    value 12
    

    Reference

    History

    • 2019/11/08: created.

    Copyright

    Copyright

  • 相关阅读:
    数据查询语句
    数据操作语句
    数据定义语句
    linux的常用命令
    NIO/IO/AIO阻塞/非阻塞/同步/异步
    XCode使用自带SVN,SVN命令
    正则表达式大全——持续更新中。。。
    sql语句优化
    sql一些语句性能及开销优化
    高质量图片无损压缩算法
  • 原文地址:https://www.cnblogs.com/kezunlin/p/12125708.html
Copyright © 2011-2022 走看看