- /*
- * 程序的版权和版本声明部分
- * Copyright (c)2013, 烟台大学计算机学院学生
- * All rightsreserved.
- * 文件名称: object.cpp
- * 作者:王俊
- * 完成日期: 2013年 4 月 17日
- * 版本号: v1.0
- * 输入描述:无
- * 问题描述:Time为Date的友元类
- * 程序输出:略。
- */
- 代码输出:
-
运行结果:#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; }; Time::Time(int a,int b,int c):hour(a),minute(b),sec(c){} Date::Date(int m,int n,int z):month(m),day(n),year(z){} void Time::add_a_second(Date &d) //增加1秒,1秒后可能会到了下一天,乃到下一月、下一年 { sec+=1; if(sec>=60){ minute+=1; sec-=60; if(minute>59) { hour+=1; minute-=60; if(hour>23) { hour-=24; d.day+=1; if(d.day>29) { d.day-=30; d.month+=1; if(d.month>12) { d.month-=12; d.year+=1; } } } } } } void Time::display(Date &d) //显示时间,格式:月/日/年 时:分:秒 { cout<<d.month<<'/'<<d.day<<'/'<<d.year<<'\t'<<hour<<':'<<minute<<':'<<sec<<endl; } int main( ) { Time t1(23,59,32); Date d1(12,25,2012); for(int i=0; i<=80; i++) { t1.add_a_second(d1); t1.display(d1); } return 0; }
第七周3友元类
最新推荐文章于 2016-05-18 22:14:45 发布