日期类的实现模板

日期类的实现模板

一、进行类的定义:
1、具有成员函数:
构造函数;
print()测试函数;
析构函数。
2、数据成员:
年;
月;
日;
拥有工具函数辅助构造函数的实现。

#ifndef DATE_H
#define DATE_H

class Date
{
public:
      Date(int = 30,int = 3,int = 2020);//默认值设为2020年3月30日。
      void print() const;//使用const限定词,符合最小权限原则。
      ~Date();
private:
      int day;
      int month;
      int year;
      int checkDay(int) const;//工具函数,辅助构造函数进行有效性检查。
};
#endif

二、接口函数的实现
1、在构造函数中分别检查年,月,日,日的检查需要工具函数的辅助。
2、print()输出验证。
3、析构函数写有输出语句,可以在测试函数中验证析构函数的调用情况。

#include<iostream>
using namespace std;

#include "Date.h"//头文件

Date::Date(int dy,int mh,int yr)//构造函数
{
   if(mh > 0 && mh <= 12)
     month = mh;
   else
     month = 1;//检查月
   cout << "Invalid month (" << mh << ") set to 1.\n";

   year = yr;//年

   day = checkDay(dy);//日的检查调用工具函数

   cout << "Date object constructor for date";
   print();
   cout << endl;
}

void Date::print() const
{
   cout << day << "/" << month << "/" << year;
   cout << endl;
}

Date::~Date()//析构函数
{
   cout << "Date object destructor for date";
   print();
   cout << endl;
}

int Date::checkDay(int testDay) const //工具函数的实现
{
   static const int daysPerMonth[13]=
         {0,31,28,31,30,31,30,31,31,30,31,30,31};
   if(testDay > 0 && testDay <= daysPerMonth[month])
    return testDay;
  
   if(month == 2 && testDay == 29 && (year % 400 == 0 || (year %4 ==0 && year % 100 !=0)))
   return testDay;

   cout << "Invalid day (" << testDay << ") set to 1.\n";
   return 1;
}

三、完成。

发布了2 篇原创文章 · 获赞 15 · 访问量 148

猜你喜欢

转载自blog.csdn.net/m0_46518461/article/details/105203822
今日推荐