1. 程式人生 > >38 C++基礎-過載一元和二元運算子

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