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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/su749520/article/details/80344747

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;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页