カスタムC ++クラス2タイプコードインクリメント操作が行わとの間の差

この記事では、最初の個人的なブログ登場https://kezunlin.me/post/caef83a3/最新の内容に、ようこそ!

ユーザー定義のクラスのcppのI ++ I ++対

ガイド

コード

#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;
}

出力

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

参照

歴史

  • 2019年11月8日:作成しました。

著作権

  • 投稿者:kezunlin
  • ポストリンク:https://kezunlin.me/post/caef83a3/
  • 著作権:別途明記しない限り、このブログのすべての記事はCC BY-NC-SA 3.0の下でライセンスされています。

著作権

  • 投稿者:kezunlin
  • ポストリンク:https://kezunlin.me/post/caef83a3/
  • 著作権:別途明記しない限り、このブログのすべての記事はCC BY-NC-SA 3.0の下でライセンスされています。

おすすめ

転載: www.cnblogs.com/kezunlin/p/12125708.html