项目三:友元类
#include <iostream>
using namespace std;
class Date; //对Date类的提前引用声明
class Time
{
public:
Time(int,int,int);
void add_a_second(Date &); //增加1秒,1秒后可能会到了下一天,乃到下一月、下一年
void display(Date &); //显示时间,格式:月/日/年 时:分:秒
private:
int hour;
int minute;
int sec;
};
class Date
{
public:
Date(int,int,int);
friend class Time; //Time为Date的友元类
private:
int month;
int day;
int year;
};
Date::Date(int m,int d,int y):year(y),day(d),month(m){}
Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){}
void Time::add_a_second(Date &d)
{
sec=sec+1;
if(sec==60)
{
minute=minute+1;
sec=0;
if(minute==60)
{
hour=hour+1;
minute=0;
if(hour>=24)
{
d.day=d.day+1;
hour=0;
if(d.day==29)
{
while(d.month==2)
{
d.month=d.month+1;
}
d.day=1;
}
if(d.day==31)
{
while(d.month==4||d.month==6||d.month==9||d.month==11)
{
d.month=d.month+1;
}
d.day=1;
}
if(d.day==32)
{
while(d.month==1||d.month==3||d.month==5||d.month==7||d.month==8||d.month==10||d.month==12)
{
d.month=d.month+1;
}
d.day=1;
if(d.month==13)
{
d.year=d.year+1;
d.month=1;
}
}
}
}
}
}
void Time::display(Date &d)
{
cout<<d.year<<"/"<<d.month<<"/"<<d.day<<" "<<hour<<":"<<minute<<":"<<sec<<endl;
}
int main( )
{
Time t1(23,59,32);
Date d1(12,31,2013); //测试时,再试试Date d1(2,28,2013)会如何
for(int i=0; i<=100; i++)
{
t1.add_a_second(d1);
t1.display(d1);
}
return 0;
}
//下面定义两个类中的成员函数,要求不得再增加成员函数
//注意体会在Time的成员函数中可以调用Date类的私有数据成员
项目一:静态成员应用
#include <iostream>
using namespace std;
class Time{
public:
Time(int=0,int=0,int=0);
void show_time( );
void add_seconds(int n);
void add_minutes(int n);
void add_hours(int n);
static void change24();
static void changefrom0();
private:
static bool is_24;
static bool from0;
int hour;
int minute;
int sec;
};
bool Time::is_24=true;
bool Time::from0=false;
Time::Time(int h,int m,int s)
{
hour=h;minute=m;sec=s;
}
void Time::show_time()
{
if(is_24)
{
if(from0)
cout<<(hour<10?"0":"")<<hour<<":"<<(minute<10?"0":"")<<minute<<":"<<(sec<10?"0":"")<<sec<<endl;
else
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
else
{
if(from0)
{
if(hour<12)
{ cout<<(hour<10?"0":"")<<hour<<":"<<(minute<10?"0":"")<<minute<<":"<<(sec<10?"0":"")<<sec<<" AM"<<endl;}
else
{ cout<<((hour-12)<10?"0":"")<<hour-12<<":"<<(minute<10?"0":"")<<minute<<":"<<(sec<10?"0":"")<<sec<<" PM"<<endl;}
}
else
{
if(hour<12)
{ cout<<hour<<":"<<minute<<":"<<sec<<" AM"<<endl;}
else
{ cout<<hour-12<<":"<<minute<<":"<<sec<<" PM"<<endl;}
}
}
}
void Time::add_seconds(int n)
{
n+=sec;
minute+=n/60;
sec=n%60;
}
void Time::add_minutes(int n)
{
n+=minute;
hour+=n/60;
minute=n%60;
}
void Time::add_hours(int n)
{
hour=(hour+n)%24;
}
void Time::change24()
{
is_24=false;
}
void Time::changefrom0()
{
from0=true;
}
int main()
{
Time p1(23,14,25),p2(8,45,6);
cout<<"24小时制,不前导:"<<endl;
p1.show_time();
p2.show_time();
p1.add_hours(10);
p2.add_hours(10);
p1.changefrom0();
p2.changefrom0();
cout<<"10小时后,切换是否前导:"<<endl;
p1.show_time();
p2.show_time();
p1.change24();
p2.change24();
cout<<"换一种制式:"<<endl;
p1.show_time();
p2.show_time();
return 0;
}