无法从一个班级转换为另一个班级

时间:2017-10-12 17:39:52

标签: c++ oop

我是编程的新手,并尝试使用转换运算符函数进行类到类的转换。

我的目标是使用转换运算符功能将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();
}

1 个答案:

答案 0 :(得分:1)

我想而不是

hrs = t.hrs;
min = t.min;
sec = t.sec;
你在Time12::operator Time24()中的

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

这就是你要垃圾的原因。但是,我并不认为该功能可以做你想做的事情。它定义了从Time12Time24的转换,这是不可能的,因为Time12不知道它是AM还是PM。你想要的是operator Time12()中的Time24