1.继承与派生基础
- 被继承的类被称为基类、父类、或超类
- 继承后的新类称为子类、派生类
子类从父类获得特征称为继承
1.1 父类
#ifndef TIME_H
#define TIME_H
class CTime{
public:
CTime();
void setHour(int hour);
void setMinute(int minute);
void setSecond(int second);
int getHour();
int getMinute();
int getSecond();
private:
int m_nHour;
int m_nMinute;
int m_nSecond;
};
#endif
1.2 子类继承
头文件
#ifndef CURRENT_TIME_H
#define CURRENT_TIME_H
#include "Time.h"
// 子类 CCurrentTime 继承父类 Ctime
class CCurrentTime : public CTime{
public:
// 构造函数
CCurrentTime();
// 析构函数
~CCurrentTime();
void init();
};
#endif
cpp实现
#include<iostream>
#include "Time.h"
#include "CurrentTime.h"
using namespace std;
CCurrentTime::CCurrentTime()
{
cout<<"CCurrentTime constructor"<<endl;
}
CCurrentTime::~CCurrentTime()
{
cout<<"CCurrentTime destructor"<<endl;
}
void CCurrentTime::init()
{
time_t t = time(0);
tm tt = *localtime(&t);
// 调用父类的方法
setHour(tt.tm_hour);
setMinute(tt.tm_min);
setSecond(tt.tm_sec);
}
1.3 调用实例
#include <iostream>
#include "Time.h"
#include "CurrentTime.h"
using namespace std;
int main() {
CCurrentTime curTime;
curTime.init();
// 23:55:16
cout<<curTime.getHour()<<":"<<curTime.getMinute()<<":"<<curTime.getSecond()<<endl;
return 0;
}