首页 > 编程语言 > 详细

C++中自增和自减的实现

时间:2020-02-07 17:42:15      阅读:82      评论:0      收藏:0      [点我收藏+]

C++中自增和自减符号我们经常使用,了解它的实现方式能够更好的为自己定义的类实现自增和自减。我们首先需要了解一个知识点,自增和自减是通过重载"++"和"--"来实现的,但是普通的重载形式无法区分这两种情况,为了解决这个情况,后置版本接受一个额外的(不被使用)int类型的形参,编译器为这个形参提供一个值为0的实参

#include <iostream>
using namespace std;

class Test{
    int a;
    string str;
public:
    Test(int i, string s) : a(i), str(std::move(s)) {}

    Test &operator++(){//前置++
        ++a;
        return *this;
    }

    Test operator++(int){ //后置++,因为此处要返回局部变量,故不能使用引用
        Test ret = *this;
        ++*this;
        return ret;
    }

    Test &operator--(){//前置--
        --a;
        return *this;
    }

    Test operator--(int){ //后置--,因为此处要返回局部变量,故不能使用引用
        Test ret = *this;
        --*this;
        return ret;
    }

    friend ostream& operator<<(ostream &os, const Test &test){
        os << test.str << " : " << test.a << endl;
        return os;
    }
};

int main(){
    Test test(1, "C++");
    cout << test << endl;
    cout << "前置自增 : " << ++test << endl;
    cout << test++ << endl;
    cout << "后置自增 : " << test << endl;
    cout << "前置自减 : " << --test << endl;
    cout << test-- << endl;
    cout << "后置自减 : " << test << endl;
    return 0;
}

输出:

C++ : 1

前置自增 : C++ : 2

C++ : 2

后置自增 : C++ : 3

前置自减 : C++ : 2

C++ : 2

后置自减 : C++ : 1

C++中自增和自减的实现

原文:https://www.cnblogs.com/raysuner/p/12273136.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!