2016-11-18 21 views
-2

==演算子をオーバーロードしようとしていますが、時間、分、秒の変数を比較したいが、それらはプライベート宣言されており、ヘッダを調整することはできませんファイル。 ==演算子がオーバーロードされているコードで、それらの変数にアクセスするにはどうすればよいですか? setTimeメソッドで呼び出されるので、h、m、sとしてアクセスすることもできません。クラスのプライベート変数にアクセスするC++

// 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 

.cppファイル

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 operator==(Time &t1, Time &t2) 
{ 
    return (t1.hour==t2.hour); 
} 
+0

'Time Time :: operator ==(Time&t1、Time&t2)'が実行します。あなたは何かを欠いている。 – DeiDei

+1

hファイルとcppファイルの '演算子=='は同じではありません。 cppファイルをhファイルに合わせてください。 –

答えて

2

あなたはここで

bool Time::operator==(const Time& t) const 
{ 
    return hour == t.hour && min == t.min && sec == t.sec; 
} 
+0

どのようにしてt.hourにアクセスできますか? – cokceken

+0

メンバー関数です。あなたは "t.hour"と書く。 – molbdnilo

+0

だから、あなたはこの時間を言うことができますが、t.hourは言うことができません。他のいくつかのクラスでは、i overload ==演算子があるとします。自分のプライベート変数にアクセスできますか? – cokceken

0

を定義する必要がありますので、あなたが実装することになっている==オペレータは、メンバ関数では、トリックです:

bool operator==(Time &t1, Time &t2) 
{ 
    return !(t1 != t2); 
} 
bool operator!=(const Time& t1, const Time& t2) 
{ 
    return t1.hour != t2.hour || t1.min != t2.min || t1.sec != t2.sec; 
} 

あなたの演算子のあなたのプライベートフィールド==関数。しかし、あなたの演算子!=は友人として定義されているので、あなたはそこでそれを行うことができます。

+0

あなたはアクセスできません.2時間です。それは専用です – cokceken

+0

はい、関数演算子==ではアクセスできませんが、関数演算子でアクセスできます!= – Michael

+0

非メンバ 'operator =='を実装しています - すでにメンバ 'operator =='があります。ヘッダーファイル全体がひどく設計されています。 'operator =='、 'operator <'はメンバー以外の友達でなければなりません。他のすべての比較は、これらの2つの観点から定義された非メンバーであり、友人である必要はありません。例: 'operator>'は 'rhs

関連する問題