c++入门(类和对象and继承for系统时间显示)

文件名:<1> time.h ;<2> time.cpp ;<3> CurrTime.h ;<4> CurrTime.cpp ;<5> main.cpp 。。。

1、代码:class c_CurrTime : public c_Time        //c_CurrTime类 继承 c_Time 类 

2、代码: c_Time* p = &CurrTime;  // 基类的指针只能调用基类的方法,而不能调用派生类方法
            std::cout<< p -> getHour() << ":" << p -> getMinute() << ":" << p -> getSecond() <<std::endl;


<3> CurrTime.h


  1 //文件名 CurrTime.h
  2 
  3 #ifndef CURRENT_TIME_H //防止重复包含的宏开关
  4 #define CURRENT_TIME_H
  5 
  6 #include "time.h"
  7 
  8 class c_CurrTime : public c_Time        //继承 c_Time 类 
  9 {
 10 public:
 11         c_CurrTime();
 12         ~c_CurrTime();
 13 
 14         int getHour();  //修改基类的getHour()方法
 15 
 16 public:
 17         void init_Time();
 18 };
 19 
 20 #endif

<4> CurrTime.cpp


  1 //文件名 CurrTime.cpp
  2 
  3 #include "CurrTime.h"
  4 
  5 #include <iostream>
  6 #include <ctime>        //系统时间库
  7 
  8 c_CurrTime::c_CurrTime()        //派生 构造函数
  9         :c_Time()       //调用 基类的 无参数默认 构造函数
 10 {
 11         init_Time();
 12         std::cout<< "c_CurrTime construction !" <<std::endl;
 13 
 14 }
 15 
 16 c_CurrTime::~c_CurrTime()       //派生 析构函数
 17 {
 18         std::cout<< "c_CurrTime destruction !" <<std::endl;
 19 }
 20 
 21 void c_CurrTime::init_Time()    //获取系统时间
 22 {
 23         time_t t = time (0);
 24         tm tt = *localtime(&t);
 25 
 26         setHour(tt.tm_hour);    //调用基类的方法
 27         setMinute(tt.tm_min);
 28         setSecond(tt.tm_sec);
 29 
 30 }
 31 
 32 int c_CurrTime::getHour()       //时间转为十二小时制:若小时大于12,则减掉12
 33 {
 34         int temp = c_Time::getHour();   //m_Hour为类C_Time的private成员,类c_CurrTime无法直接访问,可通过调用基类方法
 35         if(temp > 12)
 36         {
 37                 temp -= 12;
 38         }
 39         return temp;
 40 }

<5> main.cpp


  1 #include <iostream>
  2 
  3 #include "CurrTime.h"
  4 
  5 int main()
  6 {
  7         c_CurrTime CurrTime;
  8         //CurrTime.init_Time();
  9         std::cout<< CurrTime.getHour() << ":" << CurrTime.getMinute() << ":" << CurrTime.getSecond() <<std::endl;
 10         
 11         c_Time time = CurrTime;         //也可写成 c_Time time(CurrTime);
 12         std::cout<< time.getHour() << ":" << time.getMinute() << ":" << time.getSecond() <<std::endl;
 13         
 14         c_Time* p = &CurrTime;  //基类的指针只能调用基类的方法,而不能调用派生类方法
 15         std::cout<< p -> getHour() << ":" << p -> getMinute() << ":" << p -> getSecond() <<std::endl;
 16         
 17         return 0;
 18 }


编译、链接、执行



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值