一 项目1—静态成员应用
#include<iostream>
using namespace std;
class Time
{
public:
Time(int=0,int=0,int=0);
void show_time( ); //根据is_24和from0,输出适合形式-20:23:5/8:23:5 pm/08:23:05 pm
void add_seconds(int); //增加n秒钟
void add_minutes(int); //增加n分钟
void add_hours(int); //增加n小时
static void change24(); //改变静态成员is_24,在12和24时制之间转换
static void changefrom0(); //改变静态成员from0,切换是否前导0
private:
static bool is_24; //为true时,24小时制,如20:23:5;为flase,12小时制,显示为8:23:5 pm
static bool from0; //为true时,前导0,8:23:5显示为08:23:05
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()
{
int h;
if(is_24)
h=hour;
else
h=hour%12;
if(hour<10&&from0)
cout<<"0";
cout<<h<<":";
if(minute<10&&from0)
cout<<"0";
cout<<minute<<":";
if(sec<10&&from0)
cout<<"0";
cout<<sec;
if(!is_24)
{
if(hour>12)
cout<<" pm"<<endl;
else
cout<<" am"<<endl;
}
}
void Time::add_seconds(int n)
{
sec+=n;
if(sec>59)
{
add_minutes(sec/60);
sec%=60;
}
}
void Time::add_minutes(int n)
{
minute+=n;
if(minute>59)
{
add_hours(minute/60);
minute%=60;
}
}
void Time::add_hours(int n)
{
hour+=n;
if(hour>23)
hour%=24;
}
void Time::change24()
{
is_24=!is_24;
}
void Time::changefrom0()
{
from0=!from0;
}
int main( )
{
Time t1(23,14,25),t2(8,45,6);
cout<<"24小时制,不前导:"<<endl;
cout<<" t1是:";
t1.show_time();
cout<<endl;
cout<<" t2是:";
t2.show_time();
cout<<endl;
cout<<"10小时后,切换是否前导:"<<endl;
t1.add_hours(10);
t2.add_hours(10);
cout<<" t1是:";
t1.changefrom0();
t1.show_time();
cout<<endl;
cout<<" t2是:";
t2.show_time();
cout<<endl;
cout<<"换一种制式:"<<endl;
cout<<" t1是:";
t1.change24();
t1.show_time();
cout<<" t2是:";
cout<<"0";
t2.show_time();
}
二 项目3:友元类
#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;
};
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类的私有数据成员
Time::Time(int h,int m,int s):hour(h),minute(m),sec(s) {}
Date::Date(int mo,int d,int y):month(mo),day(d),year(y) {}
int day(int y,int m)
{
int s[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
if(y%400==0||(y%4==0&&y%100!=0))
{
s[1]=29;
}
return s[m-1];
}
void Time::add_a_second(Date &s)
{
sec++;
if(sec>=60)
{
minute++;
sec-=60;
}
if(minute>=60)
{
hour++;
minute-=60;
}
if(hour>23)
{
hour-=24;
s.day++;
}
if(s.day>day(s.year,s.month ))
{
s.month++;
s.day=1;
}
if(s.month>12)
{
s.year++;
s.month-=12;
}
}
void Time::display(Date &s)
{
cout<<s.month<<"月"<<s.day<<"日"<<s.year<<"年";
cout<<" "<<hour<<":"<<minute<<":"<<sec<<endl;
}
C++作业3
最新推荐文章于 2024-08-12 20:03:23 发布