2016-11-15 2 views
0

私はこの半分の書かれたクラスを与えられました。時間にオーバーロードされた演算子を使用する

using namespace std; 

#include <iostream> 
#include <iomanip> 
#include "Time.h" 

Time::Time() 
{ hour = min = sec = 0; 
} 

Time::Time(int h, int m, int s) 
{ setTime(h, m, s); 
} 

void Time::setTime(int h, int m, int s) 
{ hour = (h>=0 && h<24) ? h : 0; 
    min = (m>=0 && m<60) ? m : 0; 
    sec = (s>=0 && s<60) ? s : 0; 
} 

Time& Time::operator+=(unsigned int n) 
{ sec += n; 
    if (sec >= 60) 
    { min += sec/60; 
    sec %= 60; 
    if (min >=60) 
    { hour = (hour + min/60) % 24; 
     min %= 60; 
    } 
    } 
    return *this; 
} 

Time Time::operator+(unsigned int n) const 
{ Time tCopy(*this); 
    tCopy += n; 
    return tCopy; 
} 

Time& Time::operator++()  // prefix version 
{ *this += 1; 
    return *this; 
} 

Time Time::operator++(int n) // postfix version 
{ Time tCopy(*this); 
    *this += 1; 
    return tCopy; 
} 

ostream& operator<<(ostream &o, const Time &t) 
{ o << setfill('0') << setw(2) << t.hour << ':' << setw(2) << t.min << ':' << setw(2) << t.sec; 
    return o; 
} 

と、このヘッダファイル、

// using _TIMEX_H_ since _TIME_H_ seems to be used by some C++ systems 

#ifndef _TIMEX_H_ 
#define _TIMEX_H_ 

using namespace std; 

#include <iostream> 

class Time 
{ public: 
    Time(); 
    Time(int h, int m = 0, int s = 0); 
    void setTime(int, int, int); 
    Time operator+(unsigned int) const; 
    Time& operator+=(unsigned int); 
    Time& operator++(); // postfix version 
    Time operator++(int); // prefix version 

    // new member functions that you have to implement 

    Time operator-(unsigned int) const; 
    Time& operator-=(unsigned int); 
    Time& operator--();  // postfix version 
    Time operator--(int); // prefix version 

    bool operator==(const Time&) const; 
    bool operator<(const Time&) const; 
    bool operator>(const Time&) const; 

    private: 
    int hour, min, sec; 

    friend ostream& operator<<(ostream&, const Time&); 

    // new friend functions that you have to implement 

    friend bool operator<=(const Time&, const Time&); 
    friend bool operator>=(const Time&, const Time&); 
    friend bool operator!=(const Time&, const Time&); 

    friend unsigned int operator-(const Time&, const Time&); 
}; 

#endif 

私は他のオペレータ機能と友人の機能を実装することができると思うが、私は、私は、トラブルこれは、現在どのように機能するかをテストするための主な方法を書いを抱えていますただ、C++の学習を始めたばかりで、本当に苦労しています。これを書く方法を知らないと謝ります。前もって感謝します。

+0

これらの関数(なぜなら、 '<<'を除く)は、パブリックインターフェイスを使って完全に実装できるので、友人になるのはなぜか分かりません。 – molbdnilo

+0

私はそれが両方の種類の機能を実装できることを示すことができると思います... – Chaz

答えて

1

オーバーロードされた演算子のテストに特別なことはありません。 ただ、メインで2つのオブジェクトを作成し、このような何か書く:+ =演算子をチェックするために、今すぐ

Time t1(10,20,30),t2(1,2,3); 

を書く:

t1+=10; 

をあなたのオーバーロードされた関数は、あなたがすることもでき、自動的に呼び出されます

t1+=t2; 

唯一の違いは、次のような数です。 tの場合、タイプの時刻のオブジェクトになります。

< <オペレータをチェックするために、単に書く:

cout<<t1; 

、残りはフレンド関数によって処理されます。

これが役に立ちます。

関連する問題