0
点赞
收藏
分享

微信扫一扫

C++重载前置和后置++运算符

松鼠树屋 2022-02-01 阅读 74

重载前置和后置++运算符

C l o c k . h Clock.h Clock.h

#ifndef CPP_PRIMER_HEAD_H
#define CPP_PRIMER_HEAD_H
using namespace std;

class Clock{
public:
    Clock(int hour = 0, int minute = 0, int second = 0);
    void showTime() const ;

    //设置前置的单目运算符号重载
    Clock& operator ++ ();

    //设置后置的单目运算符号
    Clock operator ++ (int);


private:
    int hour, minute, second;
};

Clock::Clock(int hour, int minute, int second) {        //构造函数
    if (0 <= hour && hour < 24 && 0 <= minute && minute < 60
        && 0 <= second && second < 60) {
        this->hour = hour;
        this->minute = minute;
        this->second = second;
    } else
        cout << "Time error!" << endl;
}

void Clock::showTime() const {
    cout << hour << ":" << minute << ":" << second << endl;
}

Clock & Clock::operator++() {
    //前置的数的加
    second ++;
    if (second >= 60 ) {
        second -= 60;
        minute++;
        if (minute >= 60) {minute -= 60; hour = (hour + 1) % 24;}
    }
    return *this;       //返回的是自身,过程就就是自身的second + 1, 然后返回自身
}


Clock Clock::operator++(int) {  //与前置的++运算符号进行区分,但是参数列表不具体的使用
    Clock old = *this;      //创建一个副本存储原来的对象
    ++ (*this);
    return old;             //最终返回的是原先的没有动过的对象,然后对象*this进行自加
}
#endif //CPP_PRIMER_HEAD_H

m a i n . c p p main.cpp main.cpp

#include <iostream>
#include "head.h"
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    Clock myClock(23, 59, 59);
    cout << "First time output: ";
    myClock.showTime();
    cout << "Show myClock++:    ";
    (myClock++).showTime();
    cout << "Show ++myClock:    ";
    (++myClock).showTime();
    return 0;
}

结 果 显 示 结果显示

F:\CPP\cmake-build-debug\CPP_primer.exe
First time output: 23:59:59
Show myClock++:    23:59:59
Show ++myClock:    0:0:1
举报

相关推荐

0 条评论