版权声明:本文为博主原创文章,转载时请注明原作者,谢谢! https://blog.csdn.net/qq_31112205/article/details/84828658
这篇博客主要是学习C++程序设计语言有关类定义,成员函数,成员变量及运算符重载定义的知识,只是学习它的语法什么的。
Date.h文件代码:
#include<string>
class Date{
int y, m, d;
static Date default_date;
//mutable bool cache_valid; //10.2.7章节
//mutable std::string cache; //10.2.7章节
//void comput_cache_value() const; //10.2.7章节
public:
Date(int yy=0, int mm=0, int dd=0);
void print();
bool leapyear(int yy=0);
static void set_default(int,int,int);
int day() const;
int month() const;
int year() const;
Date& add_year(int);
Date& add_month(int);
Date& add_day(int);
//std::string string_rep() const; //10.2.7章节
};
inline int Date::day() const {return d;}
inline int Date::month() const {return m;}
inline int Date::year() const {return y;}
Date.cpp文件代码:
#include"Date.h"
#include<iostream>
Date::Date(int yy, int mm, int dd)
{
d = dd?dd:default_date.d;
m = mm?mm:default_date.m;
y = yy?yy:default_date.y;
}
void Date::print()
{
std::cout<<y<<" "<<m<<" "<<d<<std::endl;
}
bool Date::leapyear(int yy)
{
int n = yy?yy:this->y;
if(((n%400)==0)||(((n%100)!=0)&&((n%4)==0)))
return true;
return false;
}
Date Date::default_date(2017,12,4);
void Date::set_default(int y, int m, int d)
{
default_date = Date(y, m, d);
}
Date& Date::add_year(int n)
{
y += n;
return *this;
}
Date& Date::add_month(int n)
{
m += n;
if(12<m)
{
y += static_cast<int>(m/12);
m = m%(12*static_cast<int>(m/12));
if(m == 0)
{
m = 12;
y -= 1;
}
}
return *this;
}
Date& Date::add_day(int n)
{
int mon_day[] = {31,28,31,30,31,30,31,31,30,31,30,31};
if(leapyear())
mon_day[1] += 1;
if(d+n<=mon_day[m-1])
{
d += n;
return *this;
}
n = (n+d)-mon_day[m-1];
d = 0;
m += 1;
if(12<m)
{
m = 1;
y += 1;
}
add_day(n);
}
/*
std::string Date::string_rep() const
{
if(!cache_valid){
comput_cache_value();
cache_valid = true;
}
return cache;
}
*/
main.cpp文件代码:
#include"Date.h"
#include<iostream>
#include<Windows.h>
int main()
{
Date today = Date(2018,12,4);
today.print();
std::cout<<today.day()<<std::endl;
today.add_day(2);
std::cout<<today.day()<<std::endl;
Date leapyear = Date(2004,2,10);
leapyear.print();
leapyear.add_month(24);
leapyear.print();
leapyear.add_day(100);
leapyear.print();
Date d = Date();
d.print();
Date::set_default(2011,12,1);
Date a = Date();
a.print();
system("PAUSE");
return 0;
}
结果截图: