2017-10-12 3 views
-2

私はプログラミングに慣れていません。あるクラスから別のクラスに変換することができません

私の目的は、変換オペレータ機能を使用して24時間のクロックを12時間のクロックに変換することです(12時間と24時間の両方のクロックが表示されるはずです)。

以下は私のコードですが、12時間形式の時刻を見てみるとガベージ値が表示されます。

12時間形式で正しい時刻を表示するには、コードでどのような変更を行う必要がありますか?

#include<iostream.h> 
#include<conio.h> 

class Time24 
{ 
public: 
    int hrs; 
    int min; 
    int sec; 

    void getTime() 
    { 
    h: 
    cout<<"Enter time in hours : " ; 
    cin>>hrs; 
    if(hrs > 23 || hrs < 0) 
    { 
    cout<<"Hours cannot be greater than 23 or less than 0 "<<endl; 
    goto h; 
    } 

    m: 
    cout<<"Enter time in minutes : "; 
    cin>>min; 
    if(min > 59 || min < 0) 
    { 
    cout<<"Minutes cannot be greater than 59 or less than 0"<<endl; 
    goto m; 
    } 

    s: 
    cout<<"Enter time in seconds : "; 
    cin>>sec; 
    if(sec > 59 || sec < 0) 
    { 
    cout<<"Seconds cannot be greater than 59 or less than 0"<<endl; 
    goto s; 
    } 
    } 

    void display() 
    { 
    cout<<"Time in 24 hours format = "<<hrs<<":"<<min<<":"<<sec<<endl; 
    } 
}; 

class Time12 
{ 
    public: 
    int hrs; 
    int min; 
    int sec; 

    Time12() 
    { 
    hrs = 0; 
    min = 0; 
    sec = 0; 
    } 
    operator Time24() 
    { 
    Time24 t; 
    hrs = t.hrs; 
    min = t.min; 
    sec = t.sec; 
    cout<<"In operator function"<<endl; 
    cout<<"t,hrs ="<<t.hrs<<endl; 
    cout<<"hrs = "<<hrs<<endl; 

    if(hrs > 12) 
    { 
     hrs = hrs - 12; 
    } 

    return t; 
    } 

    void display() 
    { 
    cout<<"Time in 12 hours format = "<<hrs<<":"<<min<<":"<<sec; 
    } 
}; 


void main() 
{ 
clrscr(); 
Time24 t2; 
Time12 t1; 
t2.getTime(); 
t2.display(); 
//t1=t2; 
t2=t1; 
//t2 = Time24(t1); 
t1.display(); 
getch(); 
} 
+4

「goto」は通常悪い考えです。代わりにループを使用してください。 – user0042

+3

エラーが発生した場合は、それをコピーして質問に貼り付ける必要があります。 – NathanOliver

+0

'void main' ??これはなんですか? 'int main'確かに –

答えて

1

私はあなたがゴミを得ている理由です

t.hrs = hrs; 
t.min = min; 
t.sec = sec; 

を意味する代わりTime12::operator Time24()

hrs = t.hrs; 
min = t.min; 
sec = t.sec; 

のと仮定します。しかし、私は機能があなたがそれをやりたいと思っているとは思わない。 Time12からTime24への変換も定義されていますが、Time12はAMかPMかわかりません。あなたが望むのはoperator Time12()で、Time24です。

関連する問題