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

来源:互联网 发布:java架构师 在线课 编辑:程序博客网 时间:2024/06/15 20:39

文件名:<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 }


编译、链接、执行



原创粉丝点击