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

posted @ 2019-12-31 17:50  kezunlin  阅读(266)  评论(0编辑  收藏  举报