38 C++基础-重载一元和二元运算符

1. 重载双目运算符

例如一个 == 的demo

  • 调用如下
#include "Time.h"
#include "Date.h"
#include <iostream>

using namespace std;

int main() {

    CTime time1(12, 12, 12);
    CTime time2(12, 12, 12);

    bool bRet = time1 == time2;
    cout<<"Result = "<<bRet<<endl;

    return 0;
}
  • 头文件
#ifndef TIME_H
#define TIME_H

class CTime{
public:

    CTime(int hour, int minute, int second);

    // 双目运算符
    bool operator== (CTime& time);


private:
    int m_nHour;
    int m_nMinute;
    int m_nSecond;
};

#endif
  • 实现类
#include <iostream>
#include "Time.h"

using namespace std;

CTime::CTime(int hour, int minute, int second) {
    m_nHour = hour;
    m_nMinute = minute;
    m_nSecond = second;
}

bool CTime::operator==(CTime& time){
    if(m_nHour == time.m_nHour
        && m_nMinute == time.m_nMinute
        && m_nSecond == time.m_nSecond) {

        return true;
    }

    return false;
}

2. 单目运算符

这里已自增运算符为例

  • 调用实现
#include "Time.h"
#include "Date.h"
#include <iostream>

using namespace std;

int main() {

    CTime time(1, 1, 1);

    time ++;

    // Hour:1 Minute:1 Second:2
    cout<<"Hour:"<<time.getHour()<<" Minute:"<<time.getMinute()<<" Second:"<<time.getSecond()<<endl;


    return 0;
}
  • 头文件定义
#ifndef TIME_H
#define TIME_H

class CTime{
public:

    CTime(int hour, int minute, int second);

    CTime operator+(CTime time);

    CTime operator++();

    // 区分后置
    CTime operator++(int);

    int getHour();

    int getMinute();

    int getSecond();
private:
    int m_nHour;
    int m_nMinute;
    int m_nSecond;
};

#endif
  • 类的实现
#include <iostream>
#include "Time.h"

using namespace std;

CTime::CTime(int hour, int minute, int second) {
    m_nHour = hour;
    m_nMinute = minute;
    m_nSecond = second;
}
int CTime::getHour(){
    return m_nHour;
}

int CTime::getMinute(){
    return m_nMinute;
}

int CTime::getSecond(){
    return m_nSecond;
}


CTime CTime::operator+(CTime time){
    m_nHour = m_nHour + time.m_nHour;
    m_nMinute = m_nMinute + time.m_nMinute;
    m_nSecond = m_nSecond + time.m_nSecond;
    return *this;
}

CTime CTime::operator++(){
    CTime time(0, 0, 1);
    *this = *this + time;
    return *this;
}

// 区分后置
CTime CTime::operator++(int){
    CTime time(*this);
    CTime time2(0, 0, 1);
    *this = *this + time2;
    return *this;
}

猜你喜欢

转载自blog.csdn.net/su749520/article/details/80344747
38