重载自增自减运算符

在这里插入图片描述

注意前置运算符先++后返回,后置运算符先返回后- -

#include <iostream>
#include <iomanip>
using namespace std;

class Time {
    int h, m, s;
public:
    //Constructor & Destructor :
    Time() :h(0), m(0), s(0) {}
    Time(int hh, int mm, int ss) :h(hh), m(mm), s(ss) {}
    Time(Time& t) {
        h = t.h; m = t.m; s = t.s;
    }
    ~Time() {}

    void showTime() {
        if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59)
            cout << setw(2) << setfill('0') << h << ":" << setw(2) << setfill('0') << m << ":" << setw(2) << setfill('0') << s << endl;
        else cout << "Time error" << endl;
    }

    friend ostream& operator<<(ostream& os,const Time &t) {
        if (t.h >= 0 && t.h < 24 && t.m >= 0 && t.m <= 59 && t.s >= 0 && t.s <= 59)
            os << setw(2) << setfill('0') << t.h << ":" << setw(2) << setfill('0') << t.m << ":" << setw(2) << setfill('0') << t.s;
        else os << "error!!!";
        return os;
    }

    friend istream& operator>>(istream& is, Time &t) {
        /*int a, b, c;
        is >> a >> b >> c;
        if (a >= 0 && a < 24 && b >= 0 && b <= 59 && c >= 0 && c <= 59)
        {
            t.h = a; t.m = b; t.s = c;
        }
        else cout << "error!!!";*/
        //h = t.h; m = t.m; s = t.s;
        is >> t.h >> t.m >> t.s;
        return is;
    }

    //每次++或--都要判断是否合法
    //重写++t,前置先++后返回
    Time& operator++() {
        if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
            //合法,++后返回
            s++;
            if (s > 59) {
                m++;
                s = 0;
                if (m > 59) {
                    h++; m = 0;
                    if (h > 23) {
                        h = 0;
                    }
                }
            } 
        } 
        //非法,直接返回
       return *this;
    }

    //重写t++,后置先返回后++(即最后的返回值为未++之前的值)
    Time operator++(int){ 
        Time tmp = (*this);//记录未++之前的值,并返回此值
        if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
            //合法,++后返回
            s++;
            if (s > 59) {
                m++;
                s = 0;
                if (m > 59) {
                    h++; m = 0;
                    if (h > 23) {
                        h = 0;
                    }
                }
            }
        }
        //非法,直接返回
        return tmp;
    }

    //重写--t,前置
    Time& operator--() {
        if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
            s--;
            if (s < 0) {
                s = 59;
                m--;
                if (m < 0) {
                    m = 59;
                    h--;
                    if (h < 0) {
                        h = 23;
                    }
                }
            }
        } 
        return *this;
    }

    //重写t--,后置
    Time operator--(int) { 
        Time tmp = (*this);//记录未--之前的值,并返回此值
        if (h >= 0 && h < 24 && m >= 0 && m <= 59 && s >= 0 && s <= 59) {
            s--;
            if (s < 0) {
                s = 59;
                m--;
                if (m < 0) {
                    m = 59;
                    h--;
                    if (h < 0) {
                        h = 23;
                    }
                }
            }  
        }
        return tmp;
    }

    Time& inputTime()
    {
        int hour, min, sec;
        cin >> hour;
        cin >> min;
        cin >> sec;
        h = hour;
        m = min;
        s = sec;
        return *this;
    }
};

int main()
{
    Time t;
    int cases;
    cin >> cases;
    cout << setw(8) << left << "++t" << " ";
    cout << setw(8) << left << "--t" << " ";
    cout << setw(8) << left << "t" << " ";
    cout << setw(8) << left << "t--" << " ";
    cout << setw(8) << left << "t++" << " ";
    cout << setw(8) << left << "t" << right << endl;
    for (int i = 1; i <= cases; ++i)
    {
        cin >> t;
        cout << (++t) << " ";
        cout << (--t) << " ";
        cout << t << " ";
        cout << t-- << " ";
        cout << t++ << " ";
        cout << t << endl;
    }
}
<think>好的,我现在需要回答用户关于如何在C++和Python中重载减运算符的问题。首先,我得回忆一下相关知识点,并结合提供的引用内容来确保准确性。 对于C++部分,用户提供的引用[4]和[5]提到了运算符重载的基本概念和例子。自减运算符C++中分为前置和后置,它们的重载方式有所不同。前置版本没有参数,后置版本有一个int类型的占位参数。引用[5]中的例子是关于加法运算符重载的,但结构类似,可以借鉴如何定义成员函数和返回类型。 然后是Python部分,引用[3]提到Python通过特殊方法如__add__来重载运算符。但自减运算符在Python中并不直接存在,因为Python没有类似++或--的运算符。通常,Python中通过定义__iadd__和__isub__等就地运算符来实现类似功能,或者通过普通的加法赋值。需要明确告诉用户这一点,并给出相应的示例。 接下来,我需要组织回答的结构。先分开C++和Python两部分,分别讲解前置和后置的重载方法,并提供代码示例。同时要注意用户提到的“方法”和“示例”,所以每个部分都需要详细说明步骤。 在C++中,前置自运算符返回引用,而后置返回临时对象,这是关键点。需要确保示例代码正确展示这一点,比如使用operator++()和operator++(int)的区别。还要注意参数列表中的int占位符用于区分后置版本。 对于Python,需要解释虽然不能直接重载++,但可以通过__iadd__实现类似效果,或者通过其他方法模拟。给出使用__iadd__的例子,并说明如何调用,比如使用+=运算符。 最后,生成相关问题,确保问题涵盖应用场景、注意事项和与其他运算符的区别,这样用户可以有进一步探索的方向。 检查是否有遗漏,比如是否提到了返回类型、参数的区别,以及Python的特殊方法是否正确。确保引用的使用正确,引用[4]和[5]用于C++部分,引用[3]用于Python部分。同时注意用户可能混淆的地方,比如Python没有自运算符,需要明确说明。 总结步骤: 1. C++前置和后置自自减的重载方法,代码示例。 2. Python中模拟自自减的方式,代码示例。 3. 相关问题生成,帮助用户深入理解。</think>### 自减运算符重载方法及示例(C++/Python) #### C++中的自减运算符重载C++中,自运算符`++`和自减运算符`--`分为**前置**和**后置**两种形式,重载时需要区分它们的语法: 1. **前置运算符**:返回修改后的对象引用,无参数 2. **后置运算符**:返回修改前的临时对象,需添加`int`占位参数 **示例代码:** ```cpp class Counter { private: int value; public: Counter(int v=0) : value(v) {} // 前置++ Counter& operator++() { ++value; return *this; } // 后置++ Counter operator++(int) { Counter tmp = *this; ++value; return tmp; } // 前置-- Counter& operator--() { --value; return *this; } // 后置-- Counter operator--(int) { Counter tmp = *this; --value; return tmp; } }; ``` #### Python中的模拟实现 Python没有内置的自减运算符(`++`/`--`不可用),但可通过重载**就地运算符**`__iadd__`和`__isub__`实现类似效果: ```python class Counter: def __init__(self, value=0): self.value = value # 重载 += 运算符(模拟自) def __iadd__(self, other): if other == 1: self.value += 1 return self else: raise ValueError("仅支持自1") # 重载 -= 运算符(模拟自减) def __isub__(self, other): if other == 1: self.value -= 1 return self else: raise ValueError("仅支持自减1") # 使用示例 c = Counter() c += 1 # 自 c -= 1 # 自减 ``` #### 关键区别 | 特性 | C++ | Python | |--------------|------------------------------|----------------------| | 运算符形式 | 直接使用`++`/`--` | 必须通过`+=`/`-=`模拟 | | 返回类型 | 前置返回引用,后置返回副本 | 必须返回修改后的对象 | | 语法重载方式 | `operator++()`和`operator++(int)` | `__iadd__`和`__isub__` |
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值