В програмі 10.15 ми розглянемо випадок, коли функція перетворення розміщена у вихідному класі. В цьому випадку вона буде реалізована у вигляді операції перетворення.
#include <iostream.h>
#include <conio.h>
#include <bios.h>
#include <string.h>
class time12
{private:
int pm;
int hrs;
int mins;
public:
time12():pm(1),hrs(0),mins(0)
{ }
time12(int ap,int h,int m):pm(ap),hrs(h),mins(m)
{ }
void display() const
{cout<<hrs<<":";
if (mins<10)
cout<<'0';
cout<<mins<<"-";
if(pm)
cout<<"p.m";
else
cout<<"a.m";
}
};
class time24
{private:
int hours;
int minutes;
int seconds;
public:
time24(): hours(0),minutes(0),seconds(0)
{}
time24(int h,int m,int s):hours(h),minutes(m),seconds(s)
{}
void display()const
{if(hours<10) cout<<"0";
cout<<hours<<":";
if(minutes<10) cout<<"0";
cout<<minutes<<":";
if (seconds<10) cout<<"0";
cout <<seconds;
}
operator time12()const;
};
time24::operator time12() const
{int hrs24=hours;
int pm=hours<12?0:1;
int roundmins=seconds<30?minutes:minutes+1;
if (roundmins==60)
{roundmins=0;
++hrs24;
if (hrs24==12||hrs24==24)
pm=(pm==1)?0:1;
}
int hrs12=(hrs24<13)?hrs24:hrs24-12;
if (hrs12==0)
{hrs12=12;
pm=1;
}
return time12(pm,hrs12,roundmins);
};
////////
int main()
{clrscr();
int h,m,s;
while(1)
//набрати 24 для виходу
{cout <<"Введіть час у 24-форматі:\n";
cout <<"Години (0-23):";cin>>h;
if (h>23)
return(1);
cout <<"Хвилини";cin>>m;
cout<<"Секунди:";cin>>s;
time24 t24(h,m,s);
cout<<"Вихідний час";
t24.display();
time12 t12=t24;
cout <<"\nV 12-год формат: ";
t12.display();
cout<<"\n\n";
};
return 0;
}
Програма 10.15
У функції main() ми визначили об’єкт класу time24, названий t24, і присвоїли йому значення годин, хвилин і секунд, одержані від користувача. Ми також визначили об’єкт класу time12, названий t12, та ініціалізували його значенням об’єкту t24 в рядку
time12 t12=t24;
Оскільки це об’єкти різних класів, то для здійснення присвоювання необхідне перетворювання. Ми визначили операцію перетворення в класі time24. Її оголошення
time24::operator time12() const
Ця функція перетворює об’єкт, що її викликає, в об’єкт класу time12 і повертає функції main() об’єкт, що потім буде присвоєний змінній t12.