1. 派生类(子类)重写父类方法
1.1 例如父类是24小时制的
class CTime{
public:
int getHour();
1.2 子类定义为12小时制
#ifndef CURRENT_TIME_H
#define CURRENT_TIME_H
#include "Time.h"
// 子类 CCurrentTime 继承父类 Ctime
class CCurrentTime : public CTime{
public:
// 构造函数
CCurrentTime();
// 析构函数
~CCurrentTime();
void init();
int getHour();
};
#endif
1.3 重写方法
// 子类重写父类的getHour方法
// 返回 12 小时制
int CCurrentTime::getHour() {
int mHour = CTime::getHour();
cout<<"CCurrentTime getHour = "<<mHour <<endl;
if(mHour > 12) {
return mHour - 12;
}
}
1.4 运行结果
#include <iostream>
#include "Time.h"
#include "CurrentTime.h"
using namespace std;
int main() {
CCurrentTime curTime;
curTime.init();
cout<<curTime.getHour()<<":"<<curTime.getMinute()<<":"<<curTime.getSecond()<<endl;
return 0;
}
CCurrentTime getHour = 23
11:33:43
2. Has 关系-整体与部分关系
类包含其他类
#ifndef DATE_TIME_H
#define DATE_TIME_H
#include "Time.h"
class CDateTime {
public:
CDateTime();
~CDateTime();
CDateTime(int year, int month, int day,
int hour, int minute, int second);
void display();
private:
int m_nYear;
int m_nMonth;
int m_nDay;
// has 包含关系,类包含其他类
CTime m_ntime;
};
#endif
调用被包含函数的方法进行赋值
#include "DateTime.h"
#include <iostream>
using namespace std;
CDateTime::CDateTime(){
}
CDateTime::~CDateTime(){
}
CDateTime::CDateTime(int year, int month, int day,
int hour, int minute, int second){
m_nYear = year;
m_nMonth = month;
m_nDay = day;
m_ntime.setHour(hour);
m_ntime.setMinute(minute);
m_ntime.setSecond(second);
}
void CDateTime::display(){
cout<<m_nYear<<"-"<<m_nMonth<<"-"<<m_nDay<<" "<<m_ntime.getHour()
<<":"<<m_ntime.getMinute()<<":"<<m_ntime.getSecond()<<endl;
}
运行实例
#include <iostream>
#include "DateTime.h"
using namespace std;
int main() {
CDateTime mCDateTime(2018, 5, 20, 8, 8, 8);
mCDateTime.display();
return 0;
}