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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值